1 //===- HWAddressSanitizer.cpp - detector of uninitialized reads -------===//
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 /// \file
10 /// This file is a part of HWAddressSanitizer, an address sanity checker
11 /// based on tagged addressing.
12 //===----------------------------------------------------------------------===//
13 
14 #include "llvm/Transforms/Instrumentation/HWAddressSanitizer.h"
15 #include "llvm/ADT/MapVector.h"
16 #include "llvm/ADT/SmallVector.h"
17 #include "llvm/ADT/StringExtras.h"
18 #include "llvm/ADT/StringRef.h"
19 #include "llvm/ADT/Triple.h"
20 #include "llvm/BinaryFormat/ELF.h"
21 #include "llvm/IR/Attributes.h"
22 #include "llvm/IR/BasicBlock.h"
23 #include "llvm/IR/Constant.h"
24 #include "llvm/IR/Constants.h"
25 #include "llvm/IR/DataLayout.h"
26 #include "llvm/IR/DebugInfoMetadata.h"
27 #include "llvm/IR/DerivedTypes.h"
28 #include "llvm/IR/Function.h"
29 #include "llvm/IR/IRBuilder.h"
30 #include "llvm/IR/InlineAsm.h"
31 #include "llvm/IR/InstVisitor.h"
32 #include "llvm/IR/Instruction.h"
33 #include "llvm/IR/Instructions.h"
34 #include "llvm/IR/IntrinsicInst.h"
35 #include "llvm/IR/Intrinsics.h"
36 #include "llvm/IR/LLVMContext.h"
37 #include "llvm/IR/MDBuilder.h"
38 #include "llvm/IR/Module.h"
39 #include "llvm/IR/Type.h"
40 #include "llvm/IR/Value.h"
41 #include "llvm/InitializePasses.h"
42 #include "llvm/Pass.h"
43 #include "llvm/Support/Casting.h"
44 #include "llvm/Support/CommandLine.h"
45 #include "llvm/Support/Debug.h"
46 #include "llvm/Support/raw_ostream.h"
47 #include "llvm/Transforms/Instrumentation.h"
48 #include "llvm/Transforms/Instrumentation/AddressSanitizerCommon.h"
49 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
50 #include "llvm/Transforms/Utils/ModuleUtils.h"
51 #include "llvm/Transforms/Utils/PromoteMemToReg.h"
52 #include <sstream>
53 
54 using namespace llvm;
55 
56 #define DEBUG_TYPE "hwasan"
57 
58 static const char *const kHwasanModuleCtorName = "hwasan.module_ctor";
59 static const char *const kHwasanNoteName = "hwasan.note";
60 static const char *const kHwasanInitName = "__hwasan_init";
61 static const char *const kHwasanPersonalityThunkName =
62     "__hwasan_personality_thunk";
63 
64 static const char *const kHwasanShadowMemoryDynamicAddress =
65     "__hwasan_shadow_memory_dynamic_address";
66 
67 // Accesses sizes are powers of two: 1, 2, 4, 8, 16.
68 static const size_t kNumberOfAccessSizes = 5;
69 
70 static const size_t kDefaultShadowScale = 4;
71 static const uint64_t kDynamicShadowSentinel =
72     std::numeric_limits<uint64_t>::max();
73 static const unsigned kPointerTagShift = 56;
74 
75 static const unsigned kShadowBaseAlignment = 32;
76 
77 static cl::opt<std::string> ClMemoryAccessCallbackPrefix(
78     "hwasan-memory-access-callback-prefix",
79     cl::desc("Prefix for memory access callbacks"), cl::Hidden,
80     cl::init("__hwasan_"));
81 
82 static cl::opt<bool>
83     ClInstrumentWithCalls("hwasan-instrument-with-calls",
84                 cl::desc("instrument reads and writes with callbacks"),
85                 cl::Hidden, cl::init(false));
86 
87 static cl::opt<bool> ClInstrumentReads("hwasan-instrument-reads",
88                                        cl::desc("instrument read instructions"),
89                                        cl::Hidden, cl::init(true));
90 
91 static cl::opt<bool> ClInstrumentWrites(
92     "hwasan-instrument-writes", cl::desc("instrument write instructions"),
93     cl::Hidden, cl::init(true));
94 
95 static cl::opt<bool> ClInstrumentAtomics(
96     "hwasan-instrument-atomics",
97     cl::desc("instrument atomic instructions (rmw, cmpxchg)"), cl::Hidden,
98     cl::init(true));
99 
100 static cl::opt<bool> ClInstrumentByval("hwasan-instrument-byval",
101                                        cl::desc("instrument byval arguments"),
102                                        cl::Hidden, cl::init(true));
103 
104 static cl::opt<bool> ClRecover(
105     "hwasan-recover",
106     cl::desc("Enable recovery mode (continue-after-error)."),
107     cl::Hidden, cl::init(false));
108 
109 static cl::opt<bool> ClInstrumentStack("hwasan-instrument-stack",
110                                        cl::desc("instrument stack (allocas)"),
111                                        cl::Hidden, cl::init(true));
112 
113 static cl::opt<bool> ClUARRetagToZero(
114     "hwasan-uar-retag-to-zero",
115     cl::desc("Clear alloca tags before returning from the function to allow "
116              "non-instrumented and instrumented function calls mix. When set "
117              "to false, allocas are retagged before returning from the "
118              "function to detect use after return."),
119     cl::Hidden, cl::init(true));
120 
121 static cl::opt<bool> ClGenerateTagsWithCalls(
122     "hwasan-generate-tags-with-calls",
123     cl::desc("generate new tags with runtime library calls"), cl::Hidden,
124     cl::init(false));
125 
126 static cl::opt<bool> ClGlobals("hwasan-globals", cl::desc("Instrument globals"),
127                                cl::Hidden, cl::init(false), cl::ZeroOrMore);
128 
129 static cl::opt<int> ClMatchAllTag(
130     "hwasan-match-all-tag",
131     cl::desc("don't report bad accesses via pointers with this tag"),
132     cl::Hidden, cl::init(-1));
133 
134 static cl::opt<bool> ClEnableKhwasan(
135     "hwasan-kernel",
136     cl::desc("Enable KernelHWAddressSanitizer instrumentation"),
137     cl::Hidden, cl::init(false));
138 
139 // These flags allow to change the shadow mapping and control how shadow memory
140 // is accessed. The shadow mapping looks like:
141 //    Shadow = (Mem >> scale) + offset
142 
143 static cl::opt<uint64_t>
144     ClMappingOffset("hwasan-mapping-offset",
145                     cl::desc("HWASan shadow mapping offset [EXPERIMENTAL]"),
146                     cl::Hidden, cl::init(0));
147 
148 static cl::opt<bool>
149     ClWithIfunc("hwasan-with-ifunc",
150                 cl::desc("Access dynamic shadow through an ifunc global on "
151                          "platforms that support this"),
152                 cl::Hidden, cl::init(false));
153 
154 static cl::opt<bool> ClWithTls(
155     "hwasan-with-tls",
156     cl::desc("Access dynamic shadow through an thread-local pointer on "
157              "platforms that support this"),
158     cl::Hidden, cl::init(true));
159 
160 static cl::opt<bool>
161     ClRecordStackHistory("hwasan-record-stack-history",
162                          cl::desc("Record stack frames with tagged allocations "
163                                   "in a thread-local ring buffer"),
164                          cl::Hidden, cl::init(true));
165 static cl::opt<bool>
166     ClInstrumentMemIntrinsics("hwasan-instrument-mem-intrinsics",
167                               cl::desc("instrument memory intrinsics"),
168                               cl::Hidden, cl::init(true));
169 
170 static cl::opt<bool>
171     ClInstrumentLandingPads("hwasan-instrument-landing-pads",
172                             cl::desc("instrument landing pads"), cl::Hidden,
173                             cl::init(false), cl::ZeroOrMore);
174 
175 static cl::opt<bool> ClUseShortGranules(
176     "hwasan-use-short-granules",
177     cl::desc("use short granules in allocas and outlined checks"), cl::Hidden,
178     cl::init(false), cl::ZeroOrMore);
179 
180 static cl::opt<bool> ClInstrumentPersonalityFunctions(
181     "hwasan-instrument-personality-functions",
182     cl::desc("instrument personality functions"), cl::Hidden, cl::init(false),
183     cl::ZeroOrMore);
184 
185 static cl::opt<bool> ClInlineAllChecks("hwasan-inline-all-checks",
186                                        cl::desc("inline all checks"),
187                                        cl::Hidden, cl::init(false));
188 
189 namespace {
190 
191 /// An instrumentation pass implementing detection of addressability bugs
192 /// using tagged pointers.
193 class HWAddressSanitizer {
194 public:
195   explicit HWAddressSanitizer(Module &M, bool CompileKernel = false,
196                               bool Recover = false) : M(M) {
197     this->Recover = ClRecover.getNumOccurrences() > 0 ? ClRecover : Recover;
198     this->CompileKernel = ClEnableKhwasan.getNumOccurrences() > 0 ?
199         ClEnableKhwasan : CompileKernel;
200 
201     initializeModule();
202   }
203 
204   bool sanitizeFunction(Function &F);
205   void initializeModule();
206   void createHwasanCtorComdat();
207 
208   void initializeCallbacks(Module &M);
209 
210   Value *getDynamicShadowIfunc(IRBuilder<> &IRB);
211   Value *getDynamicShadowNonTls(IRBuilder<> &IRB);
212 
213   void untagPointerOperand(Instruction *I, Value *Addr);
214   Value *shadowBase();
215   Value *memToShadow(Value *Shadow, IRBuilder<> &IRB);
216   void instrumentMemAccessInline(Value *Ptr, bool IsWrite,
217                                  unsigned AccessSizeIndex,
218                                  Instruction *InsertBefore);
219   void instrumentMemIntrinsic(MemIntrinsic *MI);
220   bool instrumentMemAccess(InterestingMemoryOperand &O);
221   bool ignoreAccess(Value *Ptr);
222   void getInterestingMemoryOperands(
223       Instruction *I, SmallVectorImpl<InterestingMemoryOperand> &Interesting);
224 
225   bool isInterestingAlloca(const AllocaInst &AI);
226   bool tagAlloca(IRBuilder<> &IRB, AllocaInst *AI, Value *Tag, size_t Size);
227   Value *tagPointer(IRBuilder<> &IRB, Type *Ty, Value *PtrLong, Value *Tag);
228   Value *untagPointer(IRBuilder<> &IRB, Value *PtrLong);
229   bool instrumentStack(
230       SmallVectorImpl<AllocaInst *> &Allocas,
231       DenseMap<AllocaInst *, std::vector<DbgVariableIntrinsic *>> &AllocaDbgMap,
232       SmallVectorImpl<Instruction *> &RetVec, Value *StackTag);
233   Value *readRegister(IRBuilder<> &IRB, StringRef Name);
234   bool instrumentLandingPads(SmallVectorImpl<Instruction *> &RetVec);
235   Value *getNextTagWithCall(IRBuilder<> &IRB);
236   Value *getStackBaseTag(IRBuilder<> &IRB);
237   Value *getAllocaTag(IRBuilder<> &IRB, Value *StackTag, AllocaInst *AI,
238                      unsigned AllocaNo);
239   Value *getUARTag(IRBuilder<> &IRB, Value *StackTag);
240 
241   Value *getHwasanThreadSlotPtr(IRBuilder<> &IRB, Type *Ty);
242   void emitPrologue(IRBuilder<> &IRB, bool WithFrameRecord);
243 
244   void instrumentGlobal(GlobalVariable *GV, uint8_t Tag);
245   void instrumentGlobals();
246 
247   void instrumentPersonalityFunctions();
248 
249 private:
250   LLVMContext *C;
251   Module &M;
252   Triple TargetTriple;
253   FunctionCallee HWAsanMemmove, HWAsanMemcpy, HWAsanMemset;
254   FunctionCallee HWAsanHandleVfork;
255 
256   /// This struct defines the shadow mapping using the rule:
257   ///   shadow = (mem >> Scale) + Offset.
258   /// If InGlobal is true, then
259   ///   extern char __hwasan_shadow[];
260   ///   shadow = (mem >> Scale) + &__hwasan_shadow
261   /// If InTls is true, then
262   ///   extern char *__hwasan_tls;
263   ///   shadow = (mem>>Scale) + align_up(__hwasan_shadow, kShadowBaseAlignment)
264   struct ShadowMapping {
265     int Scale;
266     uint64_t Offset;
267     bool InGlobal;
268     bool InTls;
269 
270     void init(Triple &TargetTriple);
271     unsigned getObjectAlignment() const { return 1U << Scale; }
272   };
273   ShadowMapping Mapping;
274 
275   Type *VoidTy = Type::getVoidTy(M.getContext());
276   Type *IntptrTy;
277   Type *Int8PtrTy;
278   Type *Int8Ty;
279   Type *Int32Ty;
280   Type *Int64Ty = Type::getInt64Ty(M.getContext());
281 
282   bool CompileKernel;
283   bool Recover;
284   bool UseShortGranules;
285   bool InstrumentLandingPads;
286 
287   Function *HwasanCtorFunction;
288 
289   FunctionCallee HwasanMemoryAccessCallback[2][kNumberOfAccessSizes];
290   FunctionCallee HwasanMemoryAccessCallbackSized[2];
291 
292   FunctionCallee HwasanTagMemoryFunc;
293   FunctionCallee HwasanGenerateTagFunc;
294 
295   Constant *ShadowGlobal;
296 
297   Value *LocalDynamicShadow = nullptr;
298   Value *StackBaseTag = nullptr;
299   GlobalValue *ThreadPtrGlobal = nullptr;
300 };
301 
302 class HWAddressSanitizerLegacyPass : public FunctionPass {
303 public:
304   // Pass identification, replacement for typeid.
305   static char ID;
306 
307   explicit HWAddressSanitizerLegacyPass(bool CompileKernel = false,
308                                         bool Recover = false)
309       : FunctionPass(ID), CompileKernel(CompileKernel), Recover(Recover) {
310     initializeHWAddressSanitizerLegacyPassPass(
311         *PassRegistry::getPassRegistry());
312   }
313 
314   StringRef getPassName() const override { return "HWAddressSanitizer"; }
315 
316   bool doInitialization(Module &M) override {
317     HWASan = std::make_unique<HWAddressSanitizer>(M, CompileKernel, Recover);
318     return true;
319   }
320 
321   bool runOnFunction(Function &F) override {
322     return HWASan->sanitizeFunction(F);
323   }
324 
325   bool doFinalization(Module &M) override {
326     HWASan.reset();
327     return false;
328   }
329 
330 private:
331   std::unique_ptr<HWAddressSanitizer> HWASan;
332   bool CompileKernel;
333   bool Recover;
334 };
335 
336 } // end anonymous namespace
337 
338 char HWAddressSanitizerLegacyPass::ID = 0;
339 
340 INITIALIZE_PASS_BEGIN(
341     HWAddressSanitizerLegacyPass, "hwasan",
342     "HWAddressSanitizer: detect memory bugs using tagged addressing.", false,
343     false)
344 INITIALIZE_PASS_END(
345     HWAddressSanitizerLegacyPass, "hwasan",
346     "HWAddressSanitizer: detect memory bugs using tagged addressing.", false,
347     false)
348 
349 FunctionPass *llvm::createHWAddressSanitizerLegacyPassPass(bool CompileKernel,
350                                                            bool Recover) {
351   assert(!CompileKernel || Recover);
352   return new HWAddressSanitizerLegacyPass(CompileKernel, Recover);
353 }
354 
355 HWAddressSanitizerPass::HWAddressSanitizerPass(bool CompileKernel, bool Recover)
356     : CompileKernel(CompileKernel), Recover(Recover) {}
357 
358 PreservedAnalyses HWAddressSanitizerPass::run(Module &M,
359                                               ModuleAnalysisManager &MAM) {
360   HWAddressSanitizer HWASan(M, CompileKernel, Recover);
361   bool Modified = false;
362   for (Function &F : M)
363     Modified |= HWASan.sanitizeFunction(F);
364   if (Modified)
365     return PreservedAnalyses::none();
366   return PreservedAnalyses::all();
367 }
368 
369 void HWAddressSanitizer::createHwasanCtorComdat() {
370   std::tie(HwasanCtorFunction, std::ignore) =
371       getOrCreateSanitizerCtorAndInitFunctions(
372           M, kHwasanModuleCtorName, kHwasanInitName,
373           /*InitArgTypes=*/{},
374           /*InitArgs=*/{},
375           // This callback is invoked when the functions are created the first
376           // time. Hook them into the global ctors list in that case:
377           [&](Function *Ctor, FunctionCallee) {
378             Comdat *CtorComdat = M.getOrInsertComdat(kHwasanModuleCtorName);
379             Ctor->setComdat(CtorComdat);
380             appendToGlobalCtors(M, Ctor, 0, Ctor);
381           });
382 
383   // Create a note that contains pointers to the list of global
384   // descriptors. Adding a note to the output file will cause the linker to
385   // create a PT_NOTE program header pointing to the note that we can use to
386   // find the descriptor list starting from the program headers. A function
387   // provided by the runtime initializes the shadow memory for the globals by
388   // accessing the descriptor list via the note. The dynamic loader needs to
389   // call this function whenever a library is loaded.
390   //
391   // The reason why we use a note for this instead of a more conventional
392   // approach of having a global constructor pass a descriptor list pointer to
393   // the runtime is because of an order of initialization problem. With
394   // constructors we can encounter the following problematic scenario:
395   //
396   // 1) library A depends on library B and also interposes one of B's symbols
397   // 2) B's constructors are called before A's (as required for correctness)
398   // 3) during construction, B accesses one of its "own" globals (actually
399   //    interposed by A) and triggers a HWASAN failure due to the initialization
400   //    for A not having happened yet
401   //
402   // Even without interposition it is possible to run into similar situations in
403   // cases where two libraries mutually depend on each other.
404   //
405   // We only need one note per binary, so put everything for the note in a
406   // comdat. This needs to be a comdat with an .init_array section to prevent
407   // newer versions of lld from discarding the note.
408   //
409   // Create the note even if we aren't instrumenting globals. This ensures that
410   // binaries linked from object files with both instrumented and
411   // non-instrumented globals will end up with a note, even if a comdat from an
412   // object file with non-instrumented globals is selected. The note is harmless
413   // if the runtime doesn't support it, since it will just be ignored.
414   Comdat *NoteComdat = M.getOrInsertComdat(kHwasanModuleCtorName);
415 
416   Type *Int8Arr0Ty = ArrayType::get(Int8Ty, 0);
417   auto Start =
418       new GlobalVariable(M, Int8Arr0Ty, true, GlobalVariable::ExternalLinkage,
419                          nullptr, "__start_hwasan_globals");
420   Start->setVisibility(GlobalValue::HiddenVisibility);
421   Start->setDSOLocal(true);
422   auto Stop =
423       new GlobalVariable(M, Int8Arr0Ty, true, GlobalVariable::ExternalLinkage,
424                          nullptr, "__stop_hwasan_globals");
425   Stop->setVisibility(GlobalValue::HiddenVisibility);
426   Stop->setDSOLocal(true);
427 
428   // Null-terminated so actually 8 bytes, which are required in order to align
429   // the note properly.
430   auto *Name = ConstantDataArray::get(*C, "LLVM\0\0\0");
431 
432   auto *NoteTy = StructType::get(Int32Ty, Int32Ty, Int32Ty, Name->getType(),
433                                  Int32Ty, Int32Ty);
434   auto *Note =
435       new GlobalVariable(M, NoteTy, /*isConstant=*/true,
436                          GlobalValue::PrivateLinkage, nullptr, kHwasanNoteName);
437   Note->setSection(".note.hwasan.globals");
438   Note->setComdat(NoteComdat);
439   Note->setAlignment(Align(4));
440   Note->setDSOLocal(true);
441 
442   // The pointers in the note need to be relative so that the note ends up being
443   // placed in rodata, which is the standard location for notes.
444   auto CreateRelPtr = [&](Constant *Ptr) {
445     return ConstantExpr::getTrunc(
446         ConstantExpr::getSub(ConstantExpr::getPtrToInt(Ptr, Int64Ty),
447                              ConstantExpr::getPtrToInt(Note, Int64Ty)),
448         Int32Ty);
449   };
450   Note->setInitializer(ConstantStruct::getAnon(
451       {ConstantInt::get(Int32Ty, 8),                           // n_namesz
452        ConstantInt::get(Int32Ty, 8),                           // n_descsz
453        ConstantInt::get(Int32Ty, ELF::NT_LLVM_HWASAN_GLOBALS), // n_type
454        Name, CreateRelPtr(Start), CreateRelPtr(Stop)}));
455   appendToCompilerUsed(M, Note);
456 
457   // Create a zero-length global in hwasan_globals so that the linker will
458   // always create start and stop symbols.
459   auto Dummy = new GlobalVariable(
460       M, Int8Arr0Ty, /*isConstantGlobal*/ true, GlobalVariable::PrivateLinkage,
461       Constant::getNullValue(Int8Arr0Ty), "hwasan.dummy.global");
462   Dummy->setSection("hwasan_globals");
463   Dummy->setComdat(NoteComdat);
464   Dummy->setMetadata(LLVMContext::MD_associated,
465                      MDNode::get(*C, ValueAsMetadata::get(Note)));
466   appendToCompilerUsed(M, Dummy);
467 }
468 
469 /// Module-level initialization.
470 ///
471 /// inserts a call to __hwasan_init to the module's constructor list.
472 void HWAddressSanitizer::initializeModule() {
473   LLVM_DEBUG(dbgs() << "Init " << M.getName() << "\n");
474   auto &DL = M.getDataLayout();
475 
476   TargetTriple = Triple(M.getTargetTriple());
477 
478   Mapping.init(TargetTriple);
479 
480   C = &(M.getContext());
481   IRBuilder<> IRB(*C);
482   IntptrTy = IRB.getIntPtrTy(DL);
483   Int8PtrTy = IRB.getInt8PtrTy();
484   Int8Ty = IRB.getInt8Ty();
485   Int32Ty = IRB.getInt32Ty();
486 
487   HwasanCtorFunction = nullptr;
488 
489   // Older versions of Android do not have the required runtime support for
490   // short granules, global or personality function instrumentation. On other
491   // platforms we currently require using the latest version of the runtime.
492   bool NewRuntime =
493       !TargetTriple.isAndroid() || !TargetTriple.isAndroidVersionLT(30);
494 
495   UseShortGranules =
496       ClUseShortGranules.getNumOccurrences() ? ClUseShortGranules : NewRuntime;
497 
498   // If we don't have personality function support, fall back to landing pads.
499   InstrumentLandingPads = ClInstrumentLandingPads.getNumOccurrences()
500                               ? ClInstrumentLandingPads
501                               : !NewRuntime;
502 
503   if (!CompileKernel) {
504     createHwasanCtorComdat();
505     bool InstrumentGlobals =
506         ClGlobals.getNumOccurrences() ? ClGlobals : NewRuntime;
507     if (InstrumentGlobals)
508       instrumentGlobals();
509 
510     bool InstrumentPersonalityFunctions =
511         ClInstrumentPersonalityFunctions.getNumOccurrences()
512             ? ClInstrumentPersonalityFunctions
513             : NewRuntime;
514     if (InstrumentPersonalityFunctions)
515       instrumentPersonalityFunctions();
516   }
517 
518   if (!TargetTriple.isAndroid()) {
519     Constant *C = M.getOrInsertGlobal("__hwasan_tls", IntptrTy, [&] {
520       auto *GV = new GlobalVariable(M, IntptrTy, /*isConstant=*/false,
521                                     GlobalValue::ExternalLinkage, nullptr,
522                                     "__hwasan_tls", nullptr,
523                                     GlobalVariable::InitialExecTLSModel);
524       appendToCompilerUsed(M, GV);
525       return GV;
526     });
527     ThreadPtrGlobal = cast<GlobalVariable>(C);
528   }
529 }
530 
531 void HWAddressSanitizer::initializeCallbacks(Module &M) {
532   IRBuilder<> IRB(*C);
533   for (size_t AccessIsWrite = 0; AccessIsWrite <= 1; AccessIsWrite++) {
534     const std::string TypeStr = AccessIsWrite ? "store" : "load";
535     const std::string EndingStr = Recover ? "_noabort" : "";
536 
537     HwasanMemoryAccessCallbackSized[AccessIsWrite] = M.getOrInsertFunction(
538         ClMemoryAccessCallbackPrefix + TypeStr + "N" + EndingStr,
539         FunctionType::get(IRB.getVoidTy(), {IntptrTy, IntptrTy}, false));
540 
541     for (size_t AccessSizeIndex = 0; AccessSizeIndex < kNumberOfAccessSizes;
542          AccessSizeIndex++) {
543       HwasanMemoryAccessCallback[AccessIsWrite][AccessSizeIndex] =
544           M.getOrInsertFunction(
545               ClMemoryAccessCallbackPrefix + TypeStr +
546                   itostr(1ULL << AccessSizeIndex) + EndingStr,
547               FunctionType::get(IRB.getVoidTy(), {IntptrTy}, false));
548     }
549   }
550 
551   HwasanTagMemoryFunc = M.getOrInsertFunction(
552       "__hwasan_tag_memory", IRB.getVoidTy(), Int8PtrTy, Int8Ty, IntptrTy);
553   HwasanGenerateTagFunc =
554       M.getOrInsertFunction("__hwasan_generate_tag", Int8Ty);
555 
556   ShadowGlobal = M.getOrInsertGlobal("__hwasan_shadow",
557                                      ArrayType::get(IRB.getInt8Ty(), 0));
558 
559   const std::string MemIntrinCallbackPrefix =
560       CompileKernel ? std::string("") : ClMemoryAccessCallbackPrefix;
561   HWAsanMemmove = M.getOrInsertFunction(MemIntrinCallbackPrefix + "memmove",
562                                         IRB.getInt8PtrTy(), IRB.getInt8PtrTy(),
563                                         IRB.getInt8PtrTy(), IntptrTy);
564   HWAsanMemcpy = M.getOrInsertFunction(MemIntrinCallbackPrefix + "memcpy",
565                                        IRB.getInt8PtrTy(), IRB.getInt8PtrTy(),
566                                        IRB.getInt8PtrTy(), IntptrTy);
567   HWAsanMemset = M.getOrInsertFunction(MemIntrinCallbackPrefix + "memset",
568                                        IRB.getInt8PtrTy(), IRB.getInt8PtrTy(),
569                                        IRB.getInt32Ty(), IntptrTy);
570 
571   HWAsanHandleVfork =
572       M.getOrInsertFunction("__hwasan_handle_vfork", IRB.getVoidTy(), IntptrTy);
573 }
574 
575 Value *HWAddressSanitizer::getDynamicShadowIfunc(IRBuilder<> &IRB) {
576   // An empty inline asm with input reg == output reg.
577   // An opaque no-op cast, basically.
578   InlineAsm *Asm = InlineAsm::get(
579       FunctionType::get(Int8PtrTy, {ShadowGlobal->getType()}, false),
580       StringRef(""), StringRef("=r,0"),
581       /*hasSideEffects=*/false);
582   return IRB.CreateCall(Asm, {ShadowGlobal}, ".hwasan.shadow");
583 }
584 
585 Value *HWAddressSanitizer::getDynamicShadowNonTls(IRBuilder<> &IRB) {
586   // Generate code only when dynamic addressing is needed.
587   if (Mapping.Offset != kDynamicShadowSentinel)
588     return nullptr;
589 
590   if (Mapping.InGlobal) {
591     return getDynamicShadowIfunc(IRB);
592   } else {
593     Value *GlobalDynamicAddress =
594         IRB.GetInsertBlock()->getParent()->getParent()->getOrInsertGlobal(
595             kHwasanShadowMemoryDynamicAddress, Int8PtrTy);
596     return IRB.CreateLoad(Int8PtrTy, GlobalDynamicAddress);
597   }
598 }
599 
600 bool HWAddressSanitizer::ignoreAccess(Value *Ptr) {
601   // Do not instrument acesses from different address spaces; we cannot deal
602   // with them.
603   Type *PtrTy = cast<PointerType>(Ptr->getType()->getScalarType());
604   if (PtrTy->getPointerAddressSpace() != 0)
605     return true;
606 
607   // Ignore swifterror addresses.
608   // swifterror memory addresses are mem2reg promoted by instruction
609   // selection. As such they cannot have regular uses like an instrumentation
610   // function and it makes no sense to track them as memory.
611   if (Ptr->isSwiftError())
612     return true;
613 
614   return false;
615 }
616 
617 void HWAddressSanitizer::getInterestingMemoryOperands(
618     Instruction *I, SmallVectorImpl<InterestingMemoryOperand> &Interesting) {
619   // Skip memory accesses inserted by another instrumentation.
620   if (I->hasMetadata("nosanitize"))
621     return;
622 
623   // Do not instrument the load fetching the dynamic shadow address.
624   if (LocalDynamicShadow == I)
625     return;
626 
627   if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
628     if (!ClInstrumentReads || ignoreAccess(LI->getPointerOperand()))
629       return;
630     Interesting.emplace_back(I, LI->getPointerOperandIndex(), false,
631                              LI->getType(), LI->getAlign());
632   } else if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
633     if (!ClInstrumentWrites || ignoreAccess(SI->getPointerOperand()))
634       return;
635     Interesting.emplace_back(I, SI->getPointerOperandIndex(), true,
636                              SI->getValueOperand()->getType(), SI->getAlign());
637   } else if (AtomicRMWInst *RMW = dyn_cast<AtomicRMWInst>(I)) {
638     if (!ClInstrumentAtomics || ignoreAccess(RMW->getPointerOperand()))
639       return;
640     Interesting.emplace_back(I, RMW->getPointerOperandIndex(), true,
641                              RMW->getValOperand()->getType(), None);
642   } else if (AtomicCmpXchgInst *XCHG = dyn_cast<AtomicCmpXchgInst>(I)) {
643     if (!ClInstrumentAtomics || ignoreAccess(XCHG->getPointerOperand()))
644       return;
645     Interesting.emplace_back(I, XCHG->getPointerOperandIndex(), true,
646                              XCHG->getCompareOperand()->getType(), None);
647   } else if (auto CI = dyn_cast<CallInst>(I)) {
648     for (unsigned ArgNo = 0; ArgNo < CI->getNumArgOperands(); ArgNo++) {
649       if (!ClInstrumentByval || !CI->isByValArgument(ArgNo) ||
650           ignoreAccess(CI->getArgOperand(ArgNo)))
651         continue;
652       Type *Ty = CI->getParamByValType(ArgNo);
653       Interesting.emplace_back(I, ArgNo, false, Ty, Align(1));
654     }
655   }
656 }
657 
658 static unsigned getPointerOperandIndex(Instruction *I) {
659   if (LoadInst *LI = dyn_cast<LoadInst>(I))
660     return LI->getPointerOperandIndex();
661   if (StoreInst *SI = dyn_cast<StoreInst>(I))
662     return SI->getPointerOperandIndex();
663   if (AtomicRMWInst *RMW = dyn_cast<AtomicRMWInst>(I))
664     return RMW->getPointerOperandIndex();
665   if (AtomicCmpXchgInst *XCHG = dyn_cast<AtomicCmpXchgInst>(I))
666     return XCHG->getPointerOperandIndex();
667   report_fatal_error("Unexpected instruction");
668   return -1;
669 }
670 
671 static size_t TypeSizeToSizeIndex(uint32_t TypeSize) {
672   size_t Res = countTrailingZeros(TypeSize / 8);
673   assert(Res < kNumberOfAccessSizes);
674   return Res;
675 }
676 
677 void HWAddressSanitizer::untagPointerOperand(Instruction *I, Value *Addr) {
678   if (TargetTriple.isAArch64())
679     return;
680 
681   IRBuilder<> IRB(I);
682   Value *AddrLong = IRB.CreatePointerCast(Addr, IntptrTy);
683   Value *UntaggedPtr =
684       IRB.CreateIntToPtr(untagPointer(IRB, AddrLong), Addr->getType());
685   I->setOperand(getPointerOperandIndex(I), UntaggedPtr);
686 }
687 
688 Value *HWAddressSanitizer::shadowBase() {
689   if (LocalDynamicShadow)
690     return LocalDynamicShadow;
691   return ConstantExpr::getIntToPtr(ConstantInt::get(IntptrTy, Mapping.Offset),
692                                    Int8PtrTy);
693 }
694 
695 Value *HWAddressSanitizer::memToShadow(Value *Mem, IRBuilder<> &IRB) {
696   // Mem >> Scale
697   Value *Shadow = IRB.CreateLShr(Mem, Mapping.Scale);
698   if (Mapping.Offset == 0)
699     return IRB.CreateIntToPtr(Shadow, Int8PtrTy);
700   // (Mem >> Scale) + Offset
701   return IRB.CreateGEP(Int8Ty, shadowBase(), Shadow);
702 }
703 
704 void HWAddressSanitizer::instrumentMemAccessInline(Value *Ptr, bool IsWrite,
705                                                    unsigned AccessSizeIndex,
706                                                    Instruction *InsertBefore) {
707   const int64_t AccessInfo = Recover * 0x20 + IsWrite * 0x10 + AccessSizeIndex;
708   IRBuilder<> IRB(InsertBefore);
709 
710   if (!ClInlineAllChecks && TargetTriple.isAArch64() &&
711       TargetTriple.isOSBinFormatELF() && !Recover) {
712     Module *M = IRB.GetInsertBlock()->getParent()->getParent();
713     Ptr = IRB.CreateBitCast(Ptr, Int8PtrTy);
714     IRB.CreateCall(Intrinsic::getDeclaration(
715                        M, UseShortGranules
716                               ? Intrinsic::hwasan_check_memaccess_shortgranules
717                               : Intrinsic::hwasan_check_memaccess),
718                    {shadowBase(), Ptr, ConstantInt::get(Int32Ty, AccessInfo)});
719     return;
720   }
721 
722   Value *PtrLong = IRB.CreatePointerCast(Ptr, IntptrTy);
723   Value *PtrTag = IRB.CreateTrunc(IRB.CreateLShr(PtrLong, kPointerTagShift),
724                                   IRB.getInt8Ty());
725   Value *AddrLong = untagPointer(IRB, PtrLong);
726   Value *Shadow = memToShadow(AddrLong, IRB);
727   Value *MemTag = IRB.CreateLoad(Int8Ty, Shadow);
728   Value *TagMismatch = IRB.CreateICmpNE(PtrTag, MemTag);
729 
730   int matchAllTag = ClMatchAllTag.getNumOccurrences() > 0 ?
731       ClMatchAllTag : (CompileKernel ? 0xFF : -1);
732   if (matchAllTag != -1) {
733     Value *TagNotIgnored = IRB.CreateICmpNE(PtrTag,
734         ConstantInt::get(PtrTag->getType(), matchAllTag));
735     TagMismatch = IRB.CreateAnd(TagMismatch, TagNotIgnored);
736   }
737 
738   Instruction *CheckTerm =
739       SplitBlockAndInsertIfThen(TagMismatch, InsertBefore, false,
740                                 MDBuilder(*C).createBranchWeights(1, 100000));
741 
742   IRB.SetInsertPoint(CheckTerm);
743   Value *OutOfShortGranuleTagRange =
744       IRB.CreateICmpUGT(MemTag, ConstantInt::get(Int8Ty, 15));
745   Instruction *CheckFailTerm =
746       SplitBlockAndInsertIfThen(OutOfShortGranuleTagRange, CheckTerm, !Recover,
747                                 MDBuilder(*C).createBranchWeights(1, 100000));
748 
749   IRB.SetInsertPoint(CheckTerm);
750   Value *PtrLowBits = IRB.CreateTrunc(IRB.CreateAnd(PtrLong, 15), Int8Ty);
751   PtrLowBits = IRB.CreateAdd(
752       PtrLowBits, ConstantInt::get(Int8Ty, (1 << AccessSizeIndex) - 1));
753   Value *PtrLowBitsOOB = IRB.CreateICmpUGE(PtrLowBits, MemTag);
754   SplitBlockAndInsertIfThen(PtrLowBitsOOB, CheckTerm, false,
755                             MDBuilder(*C).createBranchWeights(1, 100000),
756                             nullptr, nullptr, CheckFailTerm->getParent());
757 
758   IRB.SetInsertPoint(CheckTerm);
759   Value *InlineTagAddr = IRB.CreateOr(AddrLong, 15);
760   InlineTagAddr = IRB.CreateIntToPtr(InlineTagAddr, Int8PtrTy);
761   Value *InlineTag = IRB.CreateLoad(Int8Ty, InlineTagAddr);
762   Value *InlineTagMismatch = IRB.CreateICmpNE(PtrTag, InlineTag);
763   SplitBlockAndInsertIfThen(InlineTagMismatch, CheckTerm, false,
764                             MDBuilder(*C).createBranchWeights(1, 100000),
765                             nullptr, nullptr, CheckFailTerm->getParent());
766 
767   IRB.SetInsertPoint(CheckFailTerm);
768   InlineAsm *Asm;
769   switch (TargetTriple.getArch()) {
770     case Triple::x86_64:
771       // The signal handler will find the data address in rdi.
772       Asm = InlineAsm::get(
773           FunctionType::get(IRB.getVoidTy(), {PtrLong->getType()}, false),
774           "int3\nnopl " + itostr(0x40 + AccessInfo) + "(%rax)",
775           "{rdi}",
776           /*hasSideEffects=*/true);
777       break;
778     case Triple::aarch64:
779     case Triple::aarch64_be:
780       // The signal handler will find the data address in x0.
781       Asm = InlineAsm::get(
782           FunctionType::get(IRB.getVoidTy(), {PtrLong->getType()}, false),
783           "brk #" + itostr(0x900 + AccessInfo),
784           "{x0}",
785           /*hasSideEffects=*/true);
786       break;
787     default:
788       report_fatal_error("unsupported architecture");
789   }
790   IRB.CreateCall(Asm, PtrLong);
791   if (Recover)
792     cast<BranchInst>(CheckFailTerm)->setSuccessor(0, CheckTerm->getParent());
793 }
794 
795 void HWAddressSanitizer::instrumentMemIntrinsic(MemIntrinsic *MI) {
796   IRBuilder<> IRB(MI);
797   if (isa<MemTransferInst>(MI)) {
798     IRB.CreateCall(
799         isa<MemMoveInst>(MI) ? HWAsanMemmove : HWAsanMemcpy,
800         {IRB.CreatePointerCast(MI->getOperand(0), IRB.getInt8PtrTy()),
801          IRB.CreatePointerCast(MI->getOperand(1), IRB.getInt8PtrTy()),
802          IRB.CreateIntCast(MI->getOperand(2), IntptrTy, false)});
803   } else if (isa<MemSetInst>(MI)) {
804     IRB.CreateCall(
805         HWAsanMemset,
806         {IRB.CreatePointerCast(MI->getOperand(0), IRB.getInt8PtrTy()),
807          IRB.CreateIntCast(MI->getOperand(1), IRB.getInt32Ty(), false),
808          IRB.CreateIntCast(MI->getOperand(2), IntptrTy, false)});
809   }
810   MI->eraseFromParent();
811 }
812 
813 bool HWAddressSanitizer::instrumentMemAccess(InterestingMemoryOperand &O) {
814   Value *Addr = O.getPtr();
815 
816   LLVM_DEBUG(dbgs() << "Instrumenting: " << O.getInsn() << "\n");
817 
818   if (O.MaybeMask)
819     return false; //FIXME
820 
821   IRBuilder<> IRB(O.getInsn());
822   if (isPowerOf2_64(O.TypeSize) &&
823       (O.TypeSize / 8 <= (1ULL << (kNumberOfAccessSizes - 1))) &&
824       (!O.Alignment || *O.Alignment >= (1ULL << Mapping.Scale) ||
825        *O.Alignment >= O.TypeSize / 8)) {
826     size_t AccessSizeIndex = TypeSizeToSizeIndex(O.TypeSize);
827     if (ClInstrumentWithCalls) {
828       IRB.CreateCall(HwasanMemoryAccessCallback[O.IsWrite][AccessSizeIndex],
829                      IRB.CreatePointerCast(Addr, IntptrTy));
830     } else {
831       instrumentMemAccessInline(Addr, O.IsWrite, AccessSizeIndex, O.getInsn());
832     }
833   } else {
834     IRB.CreateCall(HwasanMemoryAccessCallbackSized[O.IsWrite],
835                    {IRB.CreatePointerCast(Addr, IntptrTy),
836                     ConstantInt::get(IntptrTy, O.TypeSize / 8)});
837   }
838   untagPointerOperand(O.getInsn(), Addr);
839 
840   return true;
841 }
842 
843 static uint64_t getAllocaSizeInBytes(const AllocaInst &AI) {
844   uint64_t ArraySize = 1;
845   if (AI.isArrayAllocation()) {
846     const ConstantInt *CI = dyn_cast<ConstantInt>(AI.getArraySize());
847     assert(CI && "non-constant array size");
848     ArraySize = CI->getZExtValue();
849   }
850   Type *Ty = AI.getAllocatedType();
851   uint64_t SizeInBytes = AI.getModule()->getDataLayout().getTypeAllocSize(Ty);
852   return SizeInBytes * ArraySize;
853 }
854 
855 bool HWAddressSanitizer::tagAlloca(IRBuilder<> &IRB, AllocaInst *AI,
856                                    Value *Tag, size_t Size) {
857   size_t AlignedSize = alignTo(Size, Mapping.getObjectAlignment());
858   if (!UseShortGranules)
859     Size = AlignedSize;
860 
861   Value *JustTag = IRB.CreateTrunc(Tag, IRB.getInt8Ty());
862   if (ClInstrumentWithCalls) {
863     IRB.CreateCall(HwasanTagMemoryFunc,
864                    {IRB.CreatePointerCast(AI, Int8PtrTy), JustTag,
865                     ConstantInt::get(IntptrTy, AlignedSize)});
866   } else {
867     size_t ShadowSize = Size >> Mapping.Scale;
868     Value *ShadowPtr = memToShadow(IRB.CreatePointerCast(AI, IntptrTy), IRB);
869     // If this memset is not inlined, it will be intercepted in the hwasan
870     // runtime library. That's OK, because the interceptor skips the checks if
871     // the address is in the shadow region.
872     // FIXME: the interceptor is not as fast as real memset. Consider lowering
873     // llvm.memset right here into either a sequence of stores, or a call to
874     // hwasan_tag_memory.
875     if (ShadowSize)
876       IRB.CreateMemSet(ShadowPtr, JustTag, ShadowSize, Align(1));
877     if (Size != AlignedSize) {
878       IRB.CreateStore(
879           ConstantInt::get(Int8Ty, Size % Mapping.getObjectAlignment()),
880           IRB.CreateConstGEP1_32(Int8Ty, ShadowPtr, ShadowSize));
881       IRB.CreateStore(JustTag, IRB.CreateConstGEP1_32(
882                                    Int8Ty, IRB.CreateBitCast(AI, Int8PtrTy),
883                                    AlignedSize - 1));
884     }
885   }
886   return true;
887 }
888 
889 static unsigned RetagMask(unsigned AllocaNo) {
890   // A list of 8-bit numbers that have at most one run of non-zero bits.
891   // x = x ^ (mask << 56) can be encoded as a single armv8 instruction for these
892   // masks.
893   // The list does not include the value 255, which is used for UAR.
894   //
895   // Because we are more likely to use earlier elements of this list than later
896   // ones, it is sorted in increasing order of probability of collision with a
897   // mask allocated (temporally) nearby. The program that generated this list
898   // can be found at:
899   // https://github.com/google/sanitizers/blob/master/hwaddress-sanitizer/sort_masks.py
900   static unsigned FastMasks[] = {0,  128, 64,  192, 32,  96,  224, 112, 240,
901                                  48, 16,  120, 248, 56,  24,  8,   124, 252,
902                                  60, 28,  12,  4,   126, 254, 62,  30,  14,
903                                  6,  2,   127, 63,  31,  15,  7,   3,   1};
904   return FastMasks[AllocaNo % (sizeof(FastMasks) / sizeof(FastMasks[0]))];
905 }
906 
907 Value *HWAddressSanitizer::getNextTagWithCall(IRBuilder<> &IRB) {
908   return IRB.CreateZExt(IRB.CreateCall(HwasanGenerateTagFunc), IntptrTy);
909 }
910 
911 Value *HWAddressSanitizer::getStackBaseTag(IRBuilder<> &IRB) {
912   if (ClGenerateTagsWithCalls)
913     return getNextTagWithCall(IRB);
914   if (StackBaseTag)
915     return StackBaseTag;
916   // FIXME: use addressofreturnaddress (but implement it in aarch64 backend
917   // first).
918   Module *M = IRB.GetInsertBlock()->getParent()->getParent();
919   auto GetStackPointerFn = Intrinsic::getDeclaration(
920       M, Intrinsic::frameaddress,
921       IRB.getInt8PtrTy(M->getDataLayout().getAllocaAddrSpace()));
922   Value *StackPointer = IRB.CreateCall(
923       GetStackPointerFn, {Constant::getNullValue(IRB.getInt32Ty())});
924 
925   // Extract some entropy from the stack pointer for the tags.
926   // Take bits 20..28 (ASLR entropy) and xor with bits 0..8 (these differ
927   // between functions).
928   Value *StackPointerLong = IRB.CreatePointerCast(StackPointer, IntptrTy);
929   Value *StackTag =
930       IRB.CreateXor(StackPointerLong, IRB.CreateLShr(StackPointerLong, 20),
931                     "hwasan.stack.base.tag");
932   return StackTag;
933 }
934 
935 Value *HWAddressSanitizer::getAllocaTag(IRBuilder<> &IRB, Value *StackTag,
936                                         AllocaInst *AI, unsigned AllocaNo) {
937   if (ClGenerateTagsWithCalls)
938     return getNextTagWithCall(IRB);
939   return IRB.CreateXor(StackTag,
940                        ConstantInt::get(IntptrTy, RetagMask(AllocaNo)));
941 }
942 
943 Value *HWAddressSanitizer::getUARTag(IRBuilder<> &IRB, Value *StackTag) {
944   if (ClUARRetagToZero)
945     return ConstantInt::get(IntptrTy, 0);
946   if (ClGenerateTagsWithCalls)
947     return getNextTagWithCall(IRB);
948   return IRB.CreateXor(StackTag, ConstantInt::get(IntptrTy, 0xFFU));
949 }
950 
951 // Add a tag to an address.
952 Value *HWAddressSanitizer::tagPointer(IRBuilder<> &IRB, Type *Ty,
953                                       Value *PtrLong, Value *Tag) {
954   Value *TaggedPtrLong;
955   if (CompileKernel) {
956     // Kernel addresses have 0xFF in the most significant byte.
957     Value *ShiftedTag = IRB.CreateOr(
958         IRB.CreateShl(Tag, kPointerTagShift),
959         ConstantInt::get(IntptrTy, (1ULL << kPointerTagShift) - 1));
960     TaggedPtrLong = IRB.CreateAnd(PtrLong, ShiftedTag);
961   } else {
962     // Userspace can simply do OR (tag << 56);
963     Value *ShiftedTag = IRB.CreateShl(Tag, kPointerTagShift);
964     TaggedPtrLong = IRB.CreateOr(PtrLong, ShiftedTag);
965   }
966   return IRB.CreateIntToPtr(TaggedPtrLong, Ty);
967 }
968 
969 // Remove tag from an address.
970 Value *HWAddressSanitizer::untagPointer(IRBuilder<> &IRB, Value *PtrLong) {
971   Value *UntaggedPtrLong;
972   if (CompileKernel) {
973     // Kernel addresses have 0xFF in the most significant byte.
974     UntaggedPtrLong = IRB.CreateOr(PtrLong,
975         ConstantInt::get(PtrLong->getType(), 0xFFULL << kPointerTagShift));
976   } else {
977     // Userspace addresses have 0x00.
978     UntaggedPtrLong = IRB.CreateAnd(PtrLong,
979         ConstantInt::get(PtrLong->getType(), ~(0xFFULL << kPointerTagShift)));
980   }
981   return UntaggedPtrLong;
982 }
983 
984 Value *HWAddressSanitizer::getHwasanThreadSlotPtr(IRBuilder<> &IRB, Type *Ty) {
985   Module *M = IRB.GetInsertBlock()->getParent()->getParent();
986   if (TargetTriple.isAArch64() && TargetTriple.isAndroid()) {
987     // Android provides a fixed TLS slot for sanitizers. See TLS_SLOT_SANITIZER
988     // in Bionic's libc/private/bionic_tls.h.
989     Function *ThreadPointerFunc =
990         Intrinsic::getDeclaration(M, Intrinsic::thread_pointer);
991     Value *SlotPtr = IRB.CreatePointerCast(
992         IRB.CreateConstGEP1_32(IRB.getInt8Ty(),
993                                IRB.CreateCall(ThreadPointerFunc), 0x30),
994         Ty->getPointerTo(0));
995     return SlotPtr;
996   }
997   if (ThreadPtrGlobal)
998     return ThreadPtrGlobal;
999 
1000 
1001   return nullptr;
1002 }
1003 
1004 void HWAddressSanitizer::emitPrologue(IRBuilder<> &IRB, bool WithFrameRecord) {
1005   if (!Mapping.InTls) {
1006     LocalDynamicShadow = getDynamicShadowNonTls(IRB);
1007     return;
1008   }
1009 
1010   if (!WithFrameRecord && TargetTriple.isAndroid()) {
1011     LocalDynamicShadow = getDynamicShadowIfunc(IRB);
1012     return;
1013   }
1014 
1015   Value *SlotPtr = getHwasanThreadSlotPtr(IRB, IntptrTy);
1016   assert(SlotPtr);
1017 
1018   Value *ThreadLong = IRB.CreateLoad(IntptrTy, SlotPtr);
1019   // Extract the address field from ThreadLong. Unnecessary on AArch64 with TBI.
1020   Value *ThreadLongMaybeUntagged =
1021       TargetTriple.isAArch64() ? ThreadLong : untagPointer(IRB, ThreadLong);
1022 
1023   if (WithFrameRecord) {
1024     Function *F = IRB.GetInsertBlock()->getParent();
1025     StackBaseTag = IRB.CreateAShr(ThreadLong, 3);
1026 
1027     // Prepare ring buffer data.
1028     Value *PC;
1029     if (TargetTriple.getArch() == Triple::aarch64)
1030       PC = readRegister(IRB, "pc");
1031     else
1032       PC = IRB.CreatePtrToInt(F, IntptrTy);
1033     Module *M = F->getParent();
1034     auto GetStackPointerFn = Intrinsic::getDeclaration(
1035         M, Intrinsic::frameaddress,
1036         IRB.getInt8PtrTy(M->getDataLayout().getAllocaAddrSpace()));
1037     Value *SP = IRB.CreatePtrToInt(
1038         IRB.CreateCall(GetStackPointerFn,
1039                        {Constant::getNullValue(IRB.getInt32Ty())}),
1040         IntptrTy);
1041     // Mix SP and PC.
1042     // Assumptions:
1043     // PC is 0x0000PPPPPPPPPPPP  (48 bits are meaningful, others are zero)
1044     // SP is 0xsssssssssssSSSS0  (4 lower bits are zero)
1045     // We only really need ~20 lower non-zero bits (SSSS), so we mix like this:
1046     //       0xSSSSPPPPPPPPPPPP
1047     SP = IRB.CreateShl(SP, 44);
1048 
1049     // Store data to ring buffer.
1050     Value *RecordPtr =
1051         IRB.CreateIntToPtr(ThreadLongMaybeUntagged, IntptrTy->getPointerTo(0));
1052     IRB.CreateStore(IRB.CreateOr(PC, SP), RecordPtr);
1053 
1054     // Update the ring buffer. Top byte of ThreadLong defines the size of the
1055     // buffer in pages, it must be a power of two, and the start of the buffer
1056     // must be aligned by twice that much. Therefore wrap around of the ring
1057     // buffer is simply Addr &= ~((ThreadLong >> 56) << 12).
1058     // The use of AShr instead of LShr is due to
1059     //   https://bugs.llvm.org/show_bug.cgi?id=39030
1060     // Runtime library makes sure not to use the highest bit.
1061     Value *WrapMask = IRB.CreateXor(
1062         IRB.CreateShl(IRB.CreateAShr(ThreadLong, 56), 12, "", true, true),
1063         ConstantInt::get(IntptrTy, (uint64_t)-1));
1064     Value *ThreadLongNew = IRB.CreateAnd(
1065         IRB.CreateAdd(ThreadLong, ConstantInt::get(IntptrTy, 8)), WrapMask);
1066     IRB.CreateStore(ThreadLongNew, SlotPtr);
1067   }
1068 
1069   // Get shadow base address by aligning RecordPtr up.
1070   // Note: this is not correct if the pointer is already aligned.
1071   // Runtime library will make sure this never happens.
1072   LocalDynamicShadow = IRB.CreateAdd(
1073       IRB.CreateOr(
1074           ThreadLongMaybeUntagged,
1075           ConstantInt::get(IntptrTy, (1ULL << kShadowBaseAlignment) - 1)),
1076       ConstantInt::get(IntptrTy, 1), "hwasan.shadow");
1077   LocalDynamicShadow = IRB.CreateIntToPtr(LocalDynamicShadow, Int8PtrTy);
1078 }
1079 
1080 Value *HWAddressSanitizer::readRegister(IRBuilder<> &IRB, StringRef Name) {
1081   Module *M = IRB.GetInsertBlock()->getParent()->getParent();
1082   Function *ReadRegister =
1083       Intrinsic::getDeclaration(M, Intrinsic::read_register, IntptrTy);
1084   MDNode *MD = MDNode::get(*C, {MDString::get(*C, Name)});
1085   Value *Args[] = {MetadataAsValue::get(*C, MD)};
1086   return IRB.CreateCall(ReadRegister, Args);
1087 }
1088 
1089 bool HWAddressSanitizer::instrumentLandingPads(
1090     SmallVectorImpl<Instruction *> &LandingPadVec) {
1091   for (auto *LP : LandingPadVec) {
1092     IRBuilder<> IRB(LP->getNextNode());
1093     IRB.CreateCall(
1094         HWAsanHandleVfork,
1095         {readRegister(IRB, (TargetTriple.getArch() == Triple::x86_64) ? "rsp"
1096                                                                       : "sp")});
1097   }
1098   return true;
1099 }
1100 
1101 bool HWAddressSanitizer::instrumentStack(
1102     SmallVectorImpl<AllocaInst *> &Allocas,
1103     DenseMap<AllocaInst *, std::vector<DbgVariableIntrinsic *>> &AllocaDbgMap,
1104     SmallVectorImpl<Instruction *> &RetVec, Value *StackTag) {
1105   // Ideally, we want to calculate tagged stack base pointer, and rewrite all
1106   // alloca addresses using that. Unfortunately, offsets are not known yet
1107   // (unless we use ASan-style mega-alloca). Instead we keep the base tag in a
1108   // temp, shift-OR it into each alloca address and xor with the retag mask.
1109   // This generates one extra instruction per alloca use.
1110   for (unsigned N = 0; N < Allocas.size(); ++N) {
1111     auto *AI = Allocas[N];
1112     IRBuilder<> IRB(AI->getNextNode());
1113 
1114     // Replace uses of the alloca with tagged address.
1115     Value *Tag = getAllocaTag(IRB, StackTag, AI, N);
1116     Value *AILong = IRB.CreatePointerCast(AI, IntptrTy);
1117     Value *Replacement = tagPointer(IRB, AI->getType(), AILong, Tag);
1118     std::string Name =
1119         AI->hasName() ? AI->getName().str() : "alloca." + itostr(N);
1120     Replacement->setName(Name + ".hwasan");
1121 
1122     AI->replaceUsesWithIf(Replacement,
1123                           [AILong](Use &U) { return U.getUser() != AILong; });
1124 
1125     for (auto *DDI : AllocaDbgMap.lookup(AI)) {
1126       // Prepend "tag_offset, N" to the dwarf expression.
1127       // Tag offset logically applies to the alloca pointer, and it makes sense
1128       // to put it at the beginning of the expression.
1129       SmallVector<uint64_t, 8> NewOps = {dwarf::DW_OP_LLVM_tag_offset,
1130                                          RetagMask(N)};
1131       DDI->setArgOperand(
1132           2, MetadataAsValue::get(*C, DIExpression::prependOpcodes(
1133                                           DDI->getExpression(), NewOps)));
1134     }
1135 
1136     size_t Size = getAllocaSizeInBytes(*AI);
1137     tagAlloca(IRB, AI, Tag, Size);
1138 
1139     for (auto RI : RetVec) {
1140       IRB.SetInsertPoint(RI);
1141 
1142       // Re-tag alloca memory with the special UAR tag.
1143       Value *Tag = getUARTag(IRB, StackTag);
1144       tagAlloca(IRB, AI, Tag, alignTo(Size, Mapping.getObjectAlignment()));
1145     }
1146   }
1147 
1148   return true;
1149 }
1150 
1151 bool HWAddressSanitizer::isInterestingAlloca(const AllocaInst &AI) {
1152   return (AI.getAllocatedType()->isSized() &&
1153           // FIXME: instrument dynamic allocas, too
1154           AI.isStaticAlloca() &&
1155           // alloca() may be called with 0 size, ignore it.
1156           getAllocaSizeInBytes(AI) > 0 &&
1157           // We are only interested in allocas not promotable to registers.
1158           // Promotable allocas are common under -O0.
1159           !isAllocaPromotable(&AI) &&
1160           // inalloca allocas are not treated as static, and we don't want
1161           // dynamic alloca instrumentation for them as well.
1162           !AI.isUsedWithInAlloca() &&
1163           // swifterror allocas are register promoted by ISel
1164           !AI.isSwiftError());
1165 }
1166 
1167 bool HWAddressSanitizer::sanitizeFunction(Function &F) {
1168   if (&F == HwasanCtorFunction)
1169     return false;
1170 
1171   if (!F.hasFnAttribute(Attribute::SanitizeHWAddress))
1172     return false;
1173 
1174   LLVM_DEBUG(dbgs() << "Function: " << F.getName() << "\n");
1175 
1176   SmallVector<InterestingMemoryOperand, 16> OperandsToInstrument;
1177   SmallVector<MemIntrinsic *, 16> IntrinToInstrument;
1178   SmallVector<AllocaInst*, 8> AllocasToInstrument;
1179   SmallVector<Instruction*, 8> RetVec;
1180   SmallVector<Instruction*, 8> LandingPadVec;
1181   DenseMap<AllocaInst *, std::vector<DbgVariableIntrinsic *>> AllocaDbgMap;
1182   for (auto &BB : F) {
1183     for (auto &Inst : BB) {
1184       if (ClInstrumentStack)
1185         if (AllocaInst *AI = dyn_cast<AllocaInst>(&Inst)) {
1186           if (isInterestingAlloca(*AI))
1187             AllocasToInstrument.push_back(AI);
1188           continue;
1189         }
1190 
1191       if (isa<ReturnInst>(Inst) || isa<ResumeInst>(Inst) ||
1192           isa<CleanupReturnInst>(Inst))
1193         RetVec.push_back(&Inst);
1194 
1195       if (auto *DDI = dyn_cast<DbgVariableIntrinsic>(&Inst))
1196         if (auto *Alloca =
1197                 dyn_cast_or_null<AllocaInst>(DDI->getVariableLocation()))
1198           AllocaDbgMap[Alloca].push_back(DDI);
1199 
1200       if (InstrumentLandingPads && isa<LandingPadInst>(Inst))
1201         LandingPadVec.push_back(&Inst);
1202 
1203       getInterestingMemoryOperands(&Inst, OperandsToInstrument);
1204 
1205       if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(&Inst))
1206         IntrinToInstrument.push_back(MI);
1207     }
1208   }
1209 
1210   initializeCallbacks(*F.getParent());
1211 
1212   bool Changed = false;
1213 
1214   if (!LandingPadVec.empty())
1215     Changed |= instrumentLandingPads(LandingPadVec);
1216 
1217   if (AllocasToInstrument.empty() && F.hasPersonalityFn() &&
1218       F.getPersonalityFn()->getName() == kHwasanPersonalityThunkName) {
1219     // __hwasan_personality_thunk is a no-op for functions without an
1220     // instrumented stack, so we can drop it.
1221     F.setPersonalityFn(nullptr);
1222     Changed = true;
1223   }
1224 
1225   if (AllocasToInstrument.empty() && OperandsToInstrument.empty() &&
1226       IntrinToInstrument.empty())
1227     return Changed;
1228 
1229   assert(!LocalDynamicShadow);
1230 
1231   Instruction *InsertPt = &*F.getEntryBlock().begin();
1232   IRBuilder<> EntryIRB(InsertPt);
1233   emitPrologue(EntryIRB,
1234                /*WithFrameRecord*/ ClRecordStackHistory &&
1235                    !AllocasToInstrument.empty());
1236 
1237   if (!AllocasToInstrument.empty()) {
1238     Value *StackTag =
1239         ClGenerateTagsWithCalls ? nullptr : getStackBaseTag(EntryIRB);
1240     instrumentStack(AllocasToInstrument, AllocaDbgMap, RetVec, StackTag);
1241   }
1242   // Pad and align each of the allocas that we instrumented to stop small
1243   // uninteresting allocas from hiding in instrumented alloca's padding and so
1244   // that we have enough space to store real tags for short granules.
1245   DenseMap<AllocaInst *, AllocaInst *> AllocaToPaddedAllocaMap;
1246   for (AllocaInst *AI : AllocasToInstrument) {
1247     uint64_t Size = getAllocaSizeInBytes(*AI);
1248     uint64_t AlignedSize = alignTo(Size, Mapping.getObjectAlignment());
1249     AI->setAlignment(
1250         Align(std::max(AI->getAlignment(), Mapping.getObjectAlignment())));
1251     if (Size != AlignedSize) {
1252       Type *AllocatedType = AI->getAllocatedType();
1253       if (AI->isArrayAllocation()) {
1254         uint64_t ArraySize =
1255             cast<ConstantInt>(AI->getArraySize())->getZExtValue();
1256         AllocatedType = ArrayType::get(AllocatedType, ArraySize);
1257       }
1258       Type *TypeWithPadding = StructType::get(
1259           AllocatedType, ArrayType::get(Int8Ty, AlignedSize - Size));
1260       auto *NewAI = new AllocaInst(
1261           TypeWithPadding, AI->getType()->getAddressSpace(), nullptr, "", AI);
1262       NewAI->takeName(AI);
1263       NewAI->setAlignment(AI->getAlign());
1264       NewAI->setUsedWithInAlloca(AI->isUsedWithInAlloca());
1265       NewAI->setSwiftError(AI->isSwiftError());
1266       NewAI->copyMetadata(*AI);
1267       auto *Bitcast = new BitCastInst(NewAI, AI->getType(), "", AI);
1268       AI->replaceAllUsesWith(Bitcast);
1269       AllocaToPaddedAllocaMap[AI] = NewAI;
1270     }
1271   }
1272 
1273   if (!AllocaToPaddedAllocaMap.empty()) {
1274     for (auto &BB : F)
1275       for (auto &Inst : BB)
1276         if (auto *DVI = dyn_cast<DbgVariableIntrinsic>(&Inst))
1277           if (auto *AI =
1278                   dyn_cast_or_null<AllocaInst>(DVI->getVariableLocation()))
1279             if (auto *NewAI = AllocaToPaddedAllocaMap.lookup(AI))
1280               DVI->setArgOperand(
1281                   0, MetadataAsValue::get(*C, LocalAsMetadata::get(NewAI)));
1282     for (auto &P : AllocaToPaddedAllocaMap)
1283       P.first->eraseFromParent();
1284   }
1285 
1286   // If we split the entry block, move any allocas that were originally in the
1287   // entry block back into the entry block so that they aren't treated as
1288   // dynamic allocas.
1289   if (EntryIRB.GetInsertBlock() != &F.getEntryBlock()) {
1290     InsertPt = &*F.getEntryBlock().begin();
1291     for (auto II = EntryIRB.GetInsertBlock()->begin(),
1292               IE = EntryIRB.GetInsertBlock()->end();
1293          II != IE;) {
1294       Instruction *I = &*II++;
1295       if (auto *AI = dyn_cast<AllocaInst>(I))
1296         if (isa<ConstantInt>(AI->getArraySize()))
1297           I->moveBefore(InsertPt);
1298     }
1299   }
1300 
1301   for (auto &Operand : OperandsToInstrument)
1302     instrumentMemAccess(Operand);
1303 
1304   if (ClInstrumentMemIntrinsics && !IntrinToInstrument.empty()) {
1305     for (auto Inst : IntrinToInstrument)
1306       instrumentMemIntrinsic(cast<MemIntrinsic>(Inst));
1307   }
1308 
1309   LocalDynamicShadow = nullptr;
1310   StackBaseTag = nullptr;
1311 
1312   return true;
1313 }
1314 
1315 void HWAddressSanitizer::instrumentGlobal(GlobalVariable *GV, uint8_t Tag) {
1316   Constant *Initializer = GV->getInitializer();
1317   uint64_t SizeInBytes =
1318       M.getDataLayout().getTypeAllocSize(Initializer->getType());
1319   uint64_t NewSize = alignTo(SizeInBytes, Mapping.getObjectAlignment());
1320   if (SizeInBytes != NewSize) {
1321     // Pad the initializer out to the next multiple of 16 bytes and add the
1322     // required short granule tag.
1323     std::vector<uint8_t> Init(NewSize - SizeInBytes, 0);
1324     Init.back() = Tag;
1325     Constant *Padding = ConstantDataArray::get(*C, Init);
1326     Initializer = ConstantStruct::getAnon({Initializer, Padding});
1327   }
1328 
1329   auto *NewGV = new GlobalVariable(M, Initializer->getType(), GV->isConstant(),
1330                                    GlobalValue::ExternalLinkage, Initializer,
1331                                    GV->getName() + ".hwasan");
1332   NewGV->copyAttributesFrom(GV);
1333   NewGV->setLinkage(GlobalValue::PrivateLinkage);
1334   NewGV->copyMetadata(GV, 0);
1335   NewGV->setAlignment(
1336       MaybeAlign(std::max(GV->getAlignment(), Mapping.getObjectAlignment())));
1337 
1338   // It is invalid to ICF two globals that have different tags. In the case
1339   // where the size of the global is a multiple of the tag granularity the
1340   // contents of the globals may be the same but the tags (i.e. symbol values)
1341   // may be different, and the symbols are not considered during ICF. In the
1342   // case where the size is not a multiple of the granularity, the short granule
1343   // tags would discriminate two globals with different tags, but there would
1344   // otherwise be nothing stopping such a global from being incorrectly ICF'd
1345   // with an uninstrumented (i.e. tag 0) global that happened to have the short
1346   // granule tag in the last byte.
1347   NewGV->setUnnamedAddr(GlobalValue::UnnamedAddr::None);
1348 
1349   // Descriptor format (assuming little-endian):
1350   // bytes 0-3: relative address of global
1351   // bytes 4-6: size of global (16MB ought to be enough for anyone, but in case
1352   // it isn't, we create multiple descriptors)
1353   // byte 7: tag
1354   auto *DescriptorTy = StructType::get(Int32Ty, Int32Ty);
1355   const uint64_t MaxDescriptorSize = 0xfffff0;
1356   for (uint64_t DescriptorPos = 0; DescriptorPos < SizeInBytes;
1357        DescriptorPos += MaxDescriptorSize) {
1358     auto *Descriptor =
1359         new GlobalVariable(M, DescriptorTy, true, GlobalValue::PrivateLinkage,
1360                            nullptr, GV->getName() + ".hwasan.descriptor");
1361     auto *GVRelPtr = ConstantExpr::getTrunc(
1362         ConstantExpr::getAdd(
1363             ConstantExpr::getSub(
1364                 ConstantExpr::getPtrToInt(NewGV, Int64Ty),
1365                 ConstantExpr::getPtrToInt(Descriptor, Int64Ty)),
1366             ConstantInt::get(Int64Ty, DescriptorPos)),
1367         Int32Ty);
1368     uint32_t Size = std::min(SizeInBytes - DescriptorPos, MaxDescriptorSize);
1369     auto *SizeAndTag = ConstantInt::get(Int32Ty, Size | (uint32_t(Tag) << 24));
1370     Descriptor->setComdat(NewGV->getComdat());
1371     Descriptor->setInitializer(ConstantStruct::getAnon({GVRelPtr, SizeAndTag}));
1372     Descriptor->setSection("hwasan_globals");
1373     Descriptor->setMetadata(LLVMContext::MD_associated,
1374                             MDNode::get(*C, ValueAsMetadata::get(NewGV)));
1375     appendToCompilerUsed(M, Descriptor);
1376   }
1377 
1378   Constant *Aliasee = ConstantExpr::getIntToPtr(
1379       ConstantExpr::getAdd(
1380           ConstantExpr::getPtrToInt(NewGV, Int64Ty),
1381           ConstantInt::get(Int64Ty, uint64_t(Tag) << kPointerTagShift)),
1382       GV->getType());
1383   auto *Alias = GlobalAlias::create(GV->getValueType(), GV->getAddressSpace(),
1384                                     GV->getLinkage(), "", Aliasee, &M);
1385   Alias->setVisibility(GV->getVisibility());
1386   Alias->takeName(GV);
1387   GV->replaceAllUsesWith(Alias);
1388   GV->eraseFromParent();
1389 }
1390 
1391 void HWAddressSanitizer::instrumentGlobals() {
1392   std::vector<GlobalVariable *> Globals;
1393   for (GlobalVariable &GV : M.globals()) {
1394     if (GV.isDeclarationForLinker() || GV.getName().startswith("llvm.") ||
1395         GV.isThreadLocal())
1396       continue;
1397 
1398     // Common symbols can't have aliases point to them, so they can't be tagged.
1399     if (GV.hasCommonLinkage())
1400       continue;
1401 
1402     // Globals with custom sections may be used in __start_/__stop_ enumeration,
1403     // which would be broken both by adding tags and potentially by the extra
1404     // padding/alignment that we insert.
1405     if (GV.hasSection())
1406       continue;
1407 
1408     Globals.push_back(&GV);
1409   }
1410 
1411   MD5 Hasher;
1412   Hasher.update(M.getSourceFileName());
1413   MD5::MD5Result Hash;
1414   Hasher.final(Hash);
1415   uint8_t Tag = Hash[0];
1416 
1417   for (GlobalVariable *GV : Globals) {
1418     // Skip tag 0 in order to avoid collisions with untagged memory.
1419     if (Tag == 0)
1420       Tag = 1;
1421     instrumentGlobal(GV, Tag++);
1422   }
1423 }
1424 
1425 void HWAddressSanitizer::instrumentPersonalityFunctions() {
1426   // We need to untag stack frames as we unwind past them. That is the job of
1427   // the personality function wrapper, which either wraps an existing
1428   // personality function or acts as a personality function on its own. Each
1429   // function that has a personality function or that can be unwound past has
1430   // its personality function changed to a thunk that calls the personality
1431   // function wrapper in the runtime.
1432   MapVector<Constant *, std::vector<Function *>> PersonalityFns;
1433   for (Function &F : M) {
1434     if (F.isDeclaration() || !F.hasFnAttribute(Attribute::SanitizeHWAddress))
1435       continue;
1436 
1437     if (F.hasPersonalityFn()) {
1438       PersonalityFns[F.getPersonalityFn()->stripPointerCasts()].push_back(&F);
1439     } else if (!F.hasFnAttribute(Attribute::NoUnwind)) {
1440       PersonalityFns[nullptr].push_back(&F);
1441     }
1442   }
1443 
1444   if (PersonalityFns.empty())
1445     return;
1446 
1447   FunctionCallee HwasanPersonalityWrapper = M.getOrInsertFunction(
1448       "__hwasan_personality_wrapper", Int32Ty, Int32Ty, Int32Ty, Int64Ty,
1449       Int8PtrTy, Int8PtrTy, Int8PtrTy, Int8PtrTy, Int8PtrTy);
1450   FunctionCallee UnwindGetGR = M.getOrInsertFunction("_Unwind_GetGR", VoidTy);
1451   FunctionCallee UnwindGetCFA = M.getOrInsertFunction("_Unwind_GetCFA", VoidTy);
1452 
1453   for (auto &P : PersonalityFns) {
1454     std::string ThunkName = kHwasanPersonalityThunkName;
1455     if (P.first)
1456       ThunkName += ("." + P.first->getName()).str();
1457     FunctionType *ThunkFnTy = FunctionType::get(
1458         Int32Ty, {Int32Ty, Int32Ty, Int64Ty, Int8PtrTy, Int8PtrTy}, false);
1459     bool IsLocal = P.first && (!isa<GlobalValue>(P.first) ||
1460                                cast<GlobalValue>(P.first)->hasLocalLinkage());
1461     auto *ThunkFn = Function::Create(ThunkFnTy,
1462                                      IsLocal ? GlobalValue::InternalLinkage
1463                                              : GlobalValue::LinkOnceODRLinkage,
1464                                      ThunkName, &M);
1465     if (!IsLocal) {
1466       ThunkFn->setVisibility(GlobalValue::HiddenVisibility);
1467       ThunkFn->setComdat(M.getOrInsertComdat(ThunkName));
1468     }
1469 
1470     auto *BB = BasicBlock::Create(*C, "entry", ThunkFn);
1471     IRBuilder<> IRB(BB);
1472     CallInst *WrapperCall = IRB.CreateCall(
1473         HwasanPersonalityWrapper,
1474         {ThunkFn->getArg(0), ThunkFn->getArg(1), ThunkFn->getArg(2),
1475          ThunkFn->getArg(3), ThunkFn->getArg(4),
1476          P.first ? IRB.CreateBitCast(P.first, Int8PtrTy)
1477                  : Constant::getNullValue(Int8PtrTy),
1478          IRB.CreateBitCast(UnwindGetGR.getCallee(), Int8PtrTy),
1479          IRB.CreateBitCast(UnwindGetCFA.getCallee(), Int8PtrTy)});
1480     WrapperCall->setTailCall();
1481     IRB.CreateRet(WrapperCall);
1482 
1483     for (Function *F : P.second)
1484       F->setPersonalityFn(ThunkFn);
1485   }
1486 }
1487 
1488 void HWAddressSanitizer::ShadowMapping::init(Triple &TargetTriple) {
1489   Scale = kDefaultShadowScale;
1490   if (ClMappingOffset.getNumOccurrences() > 0) {
1491     InGlobal = false;
1492     InTls = false;
1493     Offset = ClMappingOffset;
1494   } else if (ClEnableKhwasan || ClInstrumentWithCalls) {
1495     InGlobal = false;
1496     InTls = false;
1497     Offset = 0;
1498   } else if (ClWithIfunc) {
1499     InGlobal = true;
1500     InTls = false;
1501     Offset = kDynamicShadowSentinel;
1502   } else if (ClWithTls) {
1503     InGlobal = false;
1504     InTls = true;
1505     Offset = kDynamicShadowSentinel;
1506   } else {
1507     InGlobal = false;
1508     InTls = false;
1509     Offset = kDynamicShadowSentinel;
1510   }
1511 }
1512