LLVM 24.0.0git
MemorySanitizer.cpp
Go to the documentation of this file.
1//===- MemorySanitizer.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 MemorySanitizer, a detector of uninitialized
11/// reads.
12///
13/// The algorithm of the tool is similar to Memcheck
14/// (https://static.usenix.org/event/usenix05/tech/general/full_papers/seward/seward_html/usenix2005.html)
15/// We associate a few shadow bits with every byte of the application memory,
16/// poison the shadow of the malloc-ed or alloca-ed memory, load the shadow,
17/// bits on every memory read, propagate the shadow bits through some of the
18/// arithmetic instruction (including MOV), store the shadow bits on every
19/// memory write, report a bug on some other instructions (e.g. JMP) if the
20/// associated shadow is poisoned.
21///
22/// But there are differences too. The first and the major one:
23/// compiler instrumentation instead of binary instrumentation. This
24/// gives us much better register allocation, possible compiler
25/// optimizations and a fast start-up. But this brings the major issue
26/// as well: msan needs to see all program events, including system
27/// calls and reads/writes in system libraries, so we either need to
28/// compile *everything* with msan or use a binary translation
29/// component (e.g. DynamoRIO) to instrument pre-built libraries.
30/// Another difference from Memcheck is that we use 8 shadow bits per
31/// byte of application memory and use a direct shadow mapping. This
32/// greatly simplifies the instrumentation code and avoids races on
33/// shadow updates (Memcheck is single-threaded so races are not a
34/// concern there. Memcheck uses 2 shadow bits per byte with a slow
35/// path storage that uses 8 bits per byte).
36///
37/// The default value of shadow is 0, which means "clean" (not poisoned).
38///
39/// Every module initializer should call __msan_init to ensure that the
40/// shadow memory is ready. On error, __msan_warning is called. Since
41/// parameters and return values may be passed via registers, we have a
42/// specialized thread-local shadow for return values
43/// (__msan_retval_tls) and parameters (__msan_param_tls).
44///
45/// Origin tracking.
46///
47/// MemorySanitizer can track origins (allocation points) of all uninitialized
48/// values. This behavior is controlled with a flag (msan-track-origins) and is
49/// disabled by default.
50///
51/// Origins are 4-byte values created and interpreted by the runtime library.
52/// They are stored in a second shadow mapping, one 4-byte value for 4 bytes
53/// of application memory. Propagation of origins is basically a bunch of
54/// "select" instructions that pick the origin of a dirty argument, if an
55/// instruction has one.
56///
57/// Every 4 aligned, consecutive bytes of application memory have one origin
58/// value associated with them. If these bytes contain uninitialized data
59/// coming from 2 different allocations, the last store wins. Because of this,
60/// MemorySanitizer reports can show unrelated origins, but this is unlikely in
61/// practice.
62///
63/// Origins are meaningless for fully initialized values, so MemorySanitizer
64/// avoids storing origin to memory when a fully initialized value is stored.
65/// This way it avoids needless overwriting origin of the 4-byte region on
66/// a short (i.e. 1 byte) clean store, and it is also good for performance.
67///
68/// Atomic handling.
69///
70/// Ideally, every atomic store of application value should update the
71/// corresponding shadow location in an atomic way. Unfortunately, atomic store
72/// of two disjoint locations can not be done without severe slowdown.
73///
74/// Therefore, we implement an approximation that may err on the safe side.
75/// In this implementation, every atomically accessed location in the program
76/// may only change from (partially) uninitialized to fully initialized, but
77/// not the other way around. We load the shadow _after_ the application load,
78/// and we store the shadow _before_ the app store. Also, we always store clean
79/// shadow (if the application store is atomic). This way, if the store-load
80/// pair constitutes a happens-before arc, shadow store and load are correctly
81/// ordered such that the load will get either the value that was stored, or
82/// some later value (which is always clean).
83///
84/// This does not work very well with Compare-And-Swap (CAS) and
85/// Read-Modify-Write (RMW) operations. To follow the above logic, CAS and RMW
86/// must store the new shadow before the app operation, and load the shadow
87/// after the app operation. Computers don't work this way. Current
88/// implementation ignores the load aspect of CAS/RMW, always returning a clean
89/// value. It implements the store part as a simple atomic store by storing a
90/// clean shadow.
91///
92/// Instrumenting inline assembly.
93///
94/// For inline assembly code LLVM has little idea about which memory locations
95/// become initialized depending on the arguments. It can be possible to figure
96/// out which arguments are meant to point to inputs and outputs, but the
97/// actual semantics can be only visible at runtime. In the Linux kernel it's
98/// also possible that the arguments only indicate the offset for a base taken
99/// from a segment register, so it's dangerous to treat any asm() arguments as
100/// pointers. We take a conservative approach generating calls to
101/// __msan_instrument_asm_store(ptr, size)
102/// , which defer the memory unpoisoning to the runtime library.
103/// The latter can perform more complex address checks to figure out whether
104/// it's safe to touch the shadow memory.
105/// Like with atomic operations, we call __msan_instrument_asm_store() before
106/// the assembly call, so that changes to the shadow memory will be seen by
107/// other threads together with main memory initialization.
108///
109/// KernelMemorySanitizer (KMSAN) implementation.
110///
111/// The major differences between KMSAN and MSan instrumentation are:
112/// - KMSAN always tracks the origins and implies msan-keep-going=true;
113/// - KMSAN allocates shadow and origin memory for each page separately, so
114/// there are no explicit accesses to shadow and origin in the
115/// instrumentation.
116/// Shadow and origin values for a particular X-byte memory location
117/// (X=1,2,4,8) are accessed through pointers obtained via the
118/// __msan_metadata_ptr_for_load_X(ptr)
119/// __msan_metadata_ptr_for_store_X(ptr)
120/// functions. The corresponding functions check that the X-byte accesses
121/// are possible and returns the pointers to shadow and origin memory.
122/// Arbitrary sized accesses are handled with:
123/// __msan_metadata_ptr_for_load_n(ptr, size)
124/// __msan_metadata_ptr_for_store_n(ptr, size);
125/// Note that the sanitizer code has to deal with how shadow/origin pairs
126/// returned by the these functions are represented in different ABIs. In
127/// the X86_64 ABI they are returned in RDX:RAX, in PowerPC64 they are
128/// returned in r3 and r4, and in the SystemZ ABI they are written to memory
129/// pointed to by a hidden parameter.
130/// - TLS variables are stored in a single per-task struct. A call to a
131/// function __msan_get_context_state() returning a pointer to that struct
132/// is inserted into every instrumented function before the entry block;
133/// - __msan_warning() takes a 32-bit origin parameter;
134/// - local variables are poisoned with __msan_poison_alloca() upon function
135/// entry and unpoisoned with __msan_unpoison_alloca() before leaving the
136/// function;
137/// - the pass doesn't declare any global variables or add global constructors
138/// to the translation unit.
139///
140/// Also, KMSAN currently ignores uninitialized memory passed into inline asm
141/// calls, making sure we're on the safe side wrt. possible false positives.
142///
143/// KernelMemorySanitizer only supports X86_64, SystemZ and PowerPC64 at the
144/// moment.
145///
146//
147// FIXME: This sanitizer does not yet handle scalable vectors
148//
149//===----------------------------------------------------------------------===//
150
153#include "llvm/ADT/APInt.h"
154#include "llvm/ADT/ArrayRef.h"
155#include "llvm/ADT/DenseMap.h"
157#include "llvm/ADT/SetVector.h"
158#include "llvm/ADT/SmallPtrSet.h"
159#include "llvm/ADT/SmallVector.h"
161#include "llvm/ADT/StringRef.h"
165#include "llvm/IR/Argument.h"
167#include "llvm/IR/Attributes.h"
168#include "llvm/IR/BasicBlock.h"
169#include "llvm/IR/CallingConv.h"
170#include "llvm/IR/Constant.h"
171#include "llvm/IR/Constants.h"
172#include "llvm/IR/DataLayout.h"
173#include "llvm/IR/DerivedTypes.h"
174#include "llvm/IR/Function.h"
175#include "llvm/IR/GlobalValue.h"
177#include "llvm/IR/IRBuilder.h"
178#include "llvm/IR/InlineAsm.h"
179#include "llvm/IR/InstVisitor.h"
180#include "llvm/IR/InstrTypes.h"
181#include "llvm/IR/Instruction.h"
182#include "llvm/IR/Instructions.h"
184#include "llvm/IR/Intrinsics.h"
185#include "llvm/IR/IntrinsicsAArch64.h"
186#include "llvm/IR/IntrinsicsX86.h"
187#include "llvm/IR/MDBuilder.h"
188#include "llvm/IR/Module.h"
189#include "llvm/IR/Type.h"
190#include "llvm/IR/Value.h"
191#include "llvm/IR/ValueMap.h"
194#include "llvm/Support/Casting.h"
195#include "llvm/Support/Debug.h"
205#include <algorithm>
206#include <cassert>
207#include <cstddef>
208#include <cstdint>
209#include <memory>
210#include <numeric>
211#include <string>
212#include <tuple>
213
214using namespace llvm;
215
216#define DEBUG_TYPE "msan"
217
218DEBUG_COUNTER(DebugInsertCheck, "msan-insert-check",
219 "Controls which checks to insert");
220
221DEBUG_COUNTER(DebugInstrumentInstruction, "msan-instrument-instruction",
222 "Controls which instruction to instrument");
223
224static const unsigned kOriginSize = 4;
227
228// These constants must be kept in sync with the ones in msan.h.
229// TODO: increase size to match SVE/SVE2/SME/SME2 limits
230static const unsigned kParamTLSSize = 800;
231static const unsigned kRetvalTLSSize = 800;
232
233// Accesses sizes are powers of two: 1, 2, 4, 8.
234static const size_t kNumberOfAccessSizes = 4;
235
236const char kMsanModuleCtorName[] = "msan.module_ctor";
237const char kMsanInitName[] = "__msan_init";
238
239namespace {
240
241// Memory map parameters used in application-to-shadow address calculation.
242// Offset = (Addr & ~AndMask) ^ XorMask
243// Shadow = ShadowBase + Offset
244// Origin = OriginBase + Offset
245struct MemoryMapParams {
246 uint64_t AndMask;
247 uint64_t XorMask;
248 uint64_t ShadowBase;
249 uint64_t OriginBase;
250};
251
252struct PlatformMemoryMapParams {
253 const MemoryMapParams *bits32;
254 const MemoryMapParams *bits64;
255};
256
257} // end anonymous namespace
258
259// i386 Linux
260static const MemoryMapParams Linux_I386_MemoryMapParams = {
261 0x000080000000, // AndMask
262 0, // XorMask (not used)
263 0, // ShadowBase (not used)
264 0x000040000000, // OriginBase
265};
266
267// x86_64 Linux
268static const MemoryMapParams Linux_X86_64_MemoryMapParams = {
269 0, // AndMask (not used)
270 0x500000000000, // XorMask
271 0, // ShadowBase (not used)
272 0x100000000000, // OriginBase
273};
274
275// mips32 Linux
276// FIXME: Remove -msan-origin-base -msan-and-mask added by PR #109284 to tests
277// after picking good constants
278
279// mips64 Linux
280static const MemoryMapParams Linux_MIPS64_MemoryMapParams = {
281 0, // AndMask (not used)
282 0x008000000000, // XorMask
283 0, // ShadowBase (not used)
284 0x002000000000, // OriginBase
285};
286
287// ppc32 Linux
288// FIXME: Remove -msan-origin-base -msan-and-mask added by PR #109284 to tests
289// after picking good constants
290
291// ppc64 Linux
292static const MemoryMapParams Linux_PowerPC64_MemoryMapParams = {
293 0xE00000000000, // AndMask
294 0x100000000000, // XorMask
295 0x080000000000, // ShadowBase
296 0x1C0000000000, // OriginBase
297};
298
299// s390x Linux
300static const MemoryMapParams Linux_S390X_MemoryMapParams = {
301 0xC00000000000, // AndMask
302 0, // XorMask (not used)
303 0x080000000000, // ShadowBase
304 0x1C0000000000, // OriginBase
305};
306
307// arm32 Linux
308// FIXME: Remove -msan-origin-base -msan-and-mask added by PR #109284 to tests
309// after picking good constants
310
311// aarch64 Linux
312static const MemoryMapParams Linux_AArch64_MemoryMapParams = {
313 0, // AndMask (not used)
314 0x0B00000000000, // XorMask
315 0, // ShadowBase (not used)
316 0x0200000000000, // OriginBase
317};
318
319// loongarch64 Linux
320static const MemoryMapParams Linux_LoongArch64_MemoryMapParams = {
321 0, // AndMask (not used)
322 0x500000000000, // XorMask
323 0, // ShadowBase (not used)
324 0x100000000000, // OriginBase
325};
326
327// hexagon Linux
328static const MemoryMapParams Linux_Hexagon_MemoryMapParams = {
329 0, // AndMask (not used)
330 0x20000000, // XorMask
331 0, // ShadowBase (not used)
332 0x50000000, // OriginBase
333};
334
335// riscv32 Linux
336// FIXME: Remove -msan-origin-base -msan-and-mask added by PR #109284 to tests
337// after picking good constants
338
339// aarch64 FreeBSD
340static const MemoryMapParams FreeBSD_AArch64_MemoryMapParams = {
341 0x1800000000000, // AndMask
342 0x0400000000000, // XorMask
343 0x0200000000000, // ShadowBase
344 0x0700000000000, // OriginBase
345};
346
347// i386 FreeBSD
348static const MemoryMapParams FreeBSD_I386_MemoryMapParams = {
349 0x000180000000, // AndMask
350 0x000040000000, // XorMask
351 0x000020000000, // ShadowBase
352 0x000700000000, // OriginBase
353};
354
355// x86_64 FreeBSD
356static const MemoryMapParams FreeBSD_X86_64_MemoryMapParams = {
357 0xc00000000000, // AndMask
358 0x200000000000, // XorMask
359 0x100000000000, // ShadowBase
360 0x380000000000, // OriginBase
361};
362
363// x86_64 NetBSD
364static const MemoryMapParams NetBSD_X86_64_MemoryMapParams = {
365 0, // AndMask
366 0x500000000000, // XorMask
367 0, // ShadowBase
368 0x100000000000, // OriginBase
369};
370
371static const PlatformMemoryMapParams Linux_X86_MemoryMapParams = {
374};
375
376static const PlatformMemoryMapParams Linux_MIPS_MemoryMapParams = {
377 nullptr,
379};
380
381static const PlatformMemoryMapParams Linux_PowerPC_MemoryMapParams = {
382 nullptr,
384};
385
386static const PlatformMemoryMapParams Linux_S390_MemoryMapParams = {
387 nullptr,
389};
390
391static const PlatformMemoryMapParams Linux_ARM_MemoryMapParams = {
392 nullptr,
394};
395
396static const PlatformMemoryMapParams Linux_LoongArch_MemoryMapParams = {
397 nullptr,
399};
400
401static const PlatformMemoryMapParams Linux_Hexagon_MemoryMapParams_P = {
403 nullptr,
404};
405
406static const PlatformMemoryMapParams FreeBSD_ARM_MemoryMapParams = {
407 nullptr,
409};
410
411static const PlatformMemoryMapParams FreeBSD_X86_MemoryMapParams = {
414};
415
416static const PlatformMemoryMapParams NetBSD_X86_MemoryMapParams = {
417 nullptr,
419};
420
422
423namespace {
424
425/// Instrument functions of a module to detect uninitialized reads.
426///
427/// Instantiating MemorySanitizer inserts the msan runtime library API function
428/// declarations into the module if they don't exist already. Instantiating
429/// ensures the __msan_init function is in the list of global constructors for
430/// the module.
431class MemorySanitizer {
432public:
433 MemorySanitizer(const InstrumentationOptions &Opts, Module &M,
434 MemorySanitizerOptions Options)
435 : Opts(Opts), CompileKernel(Options.Kernel),
436 TrackOrigins(Options.TrackOrigins), Recover(Options.Recover),
437 EagerChecks(Options.EagerChecks) {
438 initializeModule(M);
439 }
440
441 // MSan cannot be moved or copied because of MapParams.
442 MemorySanitizer(MemorySanitizer &&) = delete;
443 MemorySanitizer &operator=(MemorySanitizer &&) = delete;
444 MemorySanitizer(const MemorySanitizer &) = delete;
445 MemorySanitizer &operator=(const MemorySanitizer &) = delete;
446
447 bool sanitizeFunction(Function &F, TargetLibraryInfo &TLI);
448
449private:
450 friend struct MemorySanitizerVisitor;
451 friend struct VarArgHelperBase;
452 friend class VarArgStackModelHelperBase;
453 friend struct VarArgAMD64Helper;
454 friend struct VarArgAArch64Helper;
455 friend struct VarArgPowerPC64Helper;
456 friend struct VarArgPowerPC32Helper;
457 friend struct VarArgSystemZHelper;
458 friend struct VarArgI386Helper;
459 friend struct VarArgGenericHelper;
460
461 void initializeModule(Module &M);
462 void initializeCallbacks(Module &M, const TargetLibraryInfo &TLI);
463 void createKernelApi(Module &M, const TargetLibraryInfo &TLI);
464 void createUserspaceApi(Module &M, const TargetLibraryInfo &TLI);
465
466 template <typename... ArgsTy>
467 FunctionCallee getOrInsertMsanMetadataFunction(Module &M, StringRef Name,
468 ArgsTy... Args);
469
470 const InstrumentationOptions &Opts;
471 /// True if we're compiling the Linux kernel.
472 bool CompileKernel;
473 /// Track origins (allocation points) of uninitialized values.
474 int TrackOrigins;
475 bool Recover;
476 bool EagerChecks;
477
478 Triple TargetTriple;
479 LLVMContext *C;
480 Type *IntptrTy; ///< Integer type with the size of a ptr in default AS.
481 Type *OriginTy;
482 PointerType *PtrTy; ///< Integer type with the size of a ptr in default AS.
483
484 // XxxTLS variables represent the per-thread state in MSan and per-task state
485 // in KMSAN.
486 // For the userspace these point to thread-local globals. In the kernel land
487 // they point to the members of a per-task struct obtained via a call to
488 // __msan_get_context_state().
489
490 /// Thread-local shadow storage for function parameters.
491 Value *ParamTLS;
492
493 /// Thread-local origin storage for function parameters.
494 Value *ParamOriginTLS;
495
496 /// Thread-local shadow storage for function return value.
497 Value *RetvalTLS;
498
499 /// Thread-local origin storage for function return value.
500 Value *RetvalOriginTLS;
501
502 /// Thread-local shadow storage for in-register va_arg function.
503 Value *VAArgTLS;
504
505 /// Thread-local shadow storage for in-register va_arg function.
506 Value *VAArgOriginTLS;
507
508 /// Thread-local shadow storage for va_arg overflow area.
509 Value *VAArgOverflowSizeTLS;
510
511 /// Are the instrumentation callbacks set up?
512 bool CallbacksInitialized = false;
513
514 /// The run-time callback to print a warning.
515 FunctionCallee WarningFn;
516
517 // These arrays are indexed by log2(AccessSize).
518 FunctionCallee MaybeWarningFn[kNumberOfAccessSizes];
519 FunctionCallee MaybeWarningVarSizeFn;
520 FunctionCallee MaybeStoreOriginFn[kNumberOfAccessSizes];
521
522 /// Run-time helper that generates a new origin value for a stack
523 /// allocation.
524 FunctionCallee MsanSetAllocaOriginWithDescriptionFn;
525 // No description version
526 FunctionCallee MsanSetAllocaOriginNoDescriptionFn;
527
528 /// Run-time helper that poisons stack on function entry.
529 FunctionCallee MsanPoisonStackFn;
530
531 /// Run-time helper that records a store (or any event) of an
532 /// uninitialized value and returns an updated origin id encoding this info.
533 FunctionCallee MsanChainOriginFn;
534
535 /// Run-time helper that paints an origin over a region.
536 FunctionCallee MsanSetOriginFn;
537
538 /// MSan runtime replacements for memmove, memcpy and memset.
539 FunctionCallee MemmoveFn, MemcpyFn, MemsetFn;
540
541 /// KMSAN callback for task-local function argument shadow.
542 StructType *MsanContextStateTy;
543 FunctionCallee MsanGetContextStateFn;
544
545 /// Functions for poisoning/unpoisoning local variables
546 FunctionCallee MsanPoisonAllocaFn, MsanUnpoisonAllocaFn;
547
548 /// Pair of shadow/origin pointers.
549 Type *MsanMetadata;
550
551 /// Each of the MsanMetadataPtrXxx functions returns a MsanMetadata.
552 FunctionCallee MsanMetadataPtrForLoadN, MsanMetadataPtrForStoreN;
553 FunctionCallee MsanMetadataPtrForLoad_1_8[4];
554 FunctionCallee MsanMetadataPtrForStore_1_8[4];
555 FunctionCallee MsanInstrumentAsmStoreFn;
556
557 /// Storage for return values of the MsanMetadataPtrXxx functions.
558 Value *MsanMetadataAlloca;
559
560 /// Helper to choose between different MsanMetadataPtrXxx().
561 FunctionCallee getKmsanShadowOriginAccessFn(bool isStore, int size);
562
563 /// Memory map parameters used in application-to-shadow calculation.
564 const MemoryMapParams *MapParams;
565
566 /// Custom memory map parameters used when -msan-shadow-base or
567 // -msan-origin-base is provided.
568 MemoryMapParams CustomMapParams;
569
570 MDNode *ColdCallWeights;
571
572 /// Branch weights for origin store.
573 MDNode *OriginStoreWeights;
574};
575
576void insertModuleCtor(const InstrumentationOptions &Opts, Module &M) {
579 /*InitArgTypes=*/{},
580 /*InitArgs=*/{},
581 // This callback is invoked when the functions are created the first
582 // time. Hook them into the global ctors list in that case:
583 [&](Function *Ctor, FunctionCallee) {
584 if (!Opts.msan_with_comdat) {
585 appendToGlobalCtors(M, Ctor, 0);
586 return;
587 }
588 Comdat *MsanCtorComdat = M.getOrInsertComdat(kMsanModuleCtorName);
589 Ctor->setComdat(MsanCtorComdat);
590 appendToGlobalCtors(M, Ctor, 0, Ctor);
591 });
592}
593
594} // end anonymous namespace
595
597 : Kernel(K), TrackOrigins(TO), Recover(R), EagerChecks(EC) {}
598
599static MemorySanitizerOptions resolveOptions(const InstrumentationOptions &Opts,
601 O.Kernel = valueOr(Opts.msan_kernel, O.Kernel);
602 O.TrackOrigins =
603 Opts.msan_track_origins.value_or(O.Kernel ? 2 : O.TrackOrigins);
604 O.Recover = valueOr(Opts.msan_keep_going, O.Kernel || O.Recover);
605 O.EagerChecks = valueOr(Opts.msan_eager_checks, O.EagerChecks);
606 return O;
607}
608
611 // Return early if nosanitize_memory module flag is present for the module.
612 if (checkIfAlreadyInstrumented(M, "nosanitize_memory"))
613 return PreservedAnalyses::all();
614 const InstrumentationOptions &Opts = getInstrumentationOptions(M);
615 MemorySanitizerOptions MSanOpts = resolveOptions(Opts, Options);
616 bool Modified = false;
617 if (!MSanOpts.Kernel) {
618 insertModuleCtor(Opts, M);
619 Modified = true;
620 }
621
622 auto &FAM = AM.getResult<FunctionAnalysisManagerModuleProxy>(M).getManager();
623 for (Function &F : M) {
624 if (F.empty())
625 continue;
626 MemorySanitizer Msan(Opts, *F.getParent(), MSanOpts);
627 Modified |=
628 Msan.sanitizeFunction(F, FAM.getResult<TargetLibraryAnalysis>(F));
629 }
630
631 if (!Modified)
632 return PreservedAnalyses::all();
633
635 // GlobalsAA is considered stateless and does not get invalidated unless
636 // explicitly invalidated; PreservedAnalyses::none() is not enough. Sanitizers
637 // make changes that require GlobalsAA to be invalidated.
638 PA.abandon<GlobalsAA>();
639 return PA;
640}
641
643 raw_ostream &OS, function_ref<StringRef(StringRef)> MapClassName2PassName) {
644 static_cast<PassInfoMixin<MemorySanitizerPass> *>(this)->printPipeline(
645 OS, MapClassName2PassName);
646 OS << '<';
647 if (Options.Recover)
648 OS << "recover;";
649 if (Options.Kernel)
650 OS << "kernel;";
651 if (Options.EagerChecks)
652 OS << "eager-checks;";
653 OS << "track-origins=" << Options.TrackOrigins;
654 OS << '>';
655}
656
657/// Create a non-const global initialized with the given string.
658///
659/// Creates a writable global for Str so that we can pass it to the
660/// run-time lib. Runtime uses first 4 bytes of the string to store the
661/// frame ID, so the string needs to be mutable.
663 StringRef Str) {
664 Constant *StrConst = ConstantDataArray::getString(M.getContext(), Str);
665 return new GlobalVariable(M, StrConst->getType(), /*isConstant=*/true,
666 GlobalValue::PrivateLinkage, StrConst, "");
667}
668
669template <typename... ArgsTy>
671MemorySanitizer::getOrInsertMsanMetadataFunction(Module &M, StringRef Name,
672 ArgsTy... Args) {
673 if (TargetTriple.getArch() == Triple::systemz) {
674 // SystemZ ABI: shadow/origin pair is returned via a hidden parameter.
675 return M.getOrInsertFunction(Name, Type::getVoidTy(*C), PtrTy,
676 std::forward<ArgsTy>(Args)...);
677 }
678
679 return M.getOrInsertFunction(Name, MsanMetadata,
680 std::forward<ArgsTy>(Args)...);
681}
682
683/// Create KMSAN API callbacks.
684void MemorySanitizer::createKernelApi(Module &M, const TargetLibraryInfo &TLI) {
685 IRBuilder<> IRB(M);
686
687 // These will be initialized in insertKmsanPrologue().
688 RetvalTLS = nullptr;
689 RetvalOriginTLS = nullptr;
690 ParamTLS = nullptr;
691 ParamOriginTLS = nullptr;
692 VAArgTLS = nullptr;
693 VAArgOriginTLS = nullptr;
694 VAArgOverflowSizeTLS = nullptr;
695
696 WarningFn = M.getOrInsertFunction("__msan_warning",
697 TLI.getAttrList(C, {0}, /*Signed=*/false),
698 IRB.getVoidTy(), IRB.getInt32Ty());
699
700 // Requests the per-task context state (kmsan_context_state*) from the
701 // runtime library.
702 MsanContextStateTy = StructType::get(
703 ArrayType::get(IRB.getInt64Ty(), kParamTLSSize / 8),
704 ArrayType::get(IRB.getInt64Ty(), kRetvalTLSSize / 8),
705 ArrayType::get(IRB.getInt64Ty(), kParamTLSSize / 8),
706 ArrayType::get(IRB.getInt64Ty(), kParamTLSSize / 8), /* va_arg_origin */
707 IRB.getInt64Ty(), ArrayType::get(OriginTy, kParamTLSSize / 4), OriginTy,
708 OriginTy);
709 MsanGetContextStateFn =
710 M.getOrInsertFunction("__msan_get_context_state", PtrTy);
711
712 MsanMetadata = StructType::get(PtrTy, PtrTy);
713
714 for (int ind = 0, size = 1; ind < 4; ind++, size <<= 1) {
715 std::string name_load =
716 "__msan_metadata_ptr_for_load_" + std::to_string(size);
717 std::string name_store =
718 "__msan_metadata_ptr_for_store_" + std::to_string(size);
719 MsanMetadataPtrForLoad_1_8[ind] =
720 getOrInsertMsanMetadataFunction(M, name_load, PtrTy);
721 MsanMetadataPtrForStore_1_8[ind] =
722 getOrInsertMsanMetadataFunction(M, name_store, PtrTy);
723 }
724
725 MsanMetadataPtrForLoadN = getOrInsertMsanMetadataFunction(
726 M, "__msan_metadata_ptr_for_load_n", PtrTy, IntptrTy);
727 MsanMetadataPtrForStoreN = getOrInsertMsanMetadataFunction(
728 M, "__msan_metadata_ptr_for_store_n", PtrTy, IntptrTy);
729
730 // Functions for poisoning and unpoisoning memory.
731 MsanPoisonAllocaFn = M.getOrInsertFunction(
732 "__msan_poison_alloca", IRB.getVoidTy(), PtrTy, IntptrTy, PtrTy);
733 MsanUnpoisonAllocaFn = M.getOrInsertFunction(
734 "__msan_unpoison_alloca", IRB.getVoidTy(), PtrTy, IntptrTy);
735}
736
738 return M.getOrInsertGlobal(Name, Ty, [&] {
739 return new GlobalVariable(M, Ty, false, GlobalVariable::ExternalLinkage,
740 nullptr, Name, nullptr,
742 });
743}
744
745/// Insert declarations for userspace-specific functions and globals.
746void MemorySanitizer::createUserspaceApi(Module &M,
747 const TargetLibraryInfo &TLI) {
748 IRBuilder<> IRB(M);
749
750 // Create the callback.
751 // FIXME: this function should have "Cold" calling conv,
752 // which is not yet implemented.
753 if (TrackOrigins) {
754 StringRef WarningFnName = Recover ? "__msan_warning_with_origin"
755 : "__msan_warning_with_origin_noreturn";
756 WarningFn = M.getOrInsertFunction(WarningFnName,
757 TLI.getAttrList(C, {0}, /*Signed=*/false),
758 IRB.getVoidTy(), IRB.getInt32Ty());
759 } else {
760 StringRef WarningFnName =
761 Recover ? "__msan_warning" : "__msan_warning_noreturn";
762 WarningFn = M.getOrInsertFunction(WarningFnName, IRB.getVoidTy());
763 }
764
765 // Create the global TLS variables.
766 RetvalTLS =
767 getOrInsertGlobal(M, "__msan_retval_tls",
768 ArrayType::get(IRB.getInt64Ty(), kRetvalTLSSize / 8));
769
770 RetvalOriginTLS = getOrInsertGlobal(M, "__msan_retval_origin_tls", OriginTy);
771
772 ParamTLS =
773 getOrInsertGlobal(M, "__msan_param_tls",
774 ArrayType::get(IRB.getInt64Ty(), kParamTLSSize / 8));
775
776 ParamOriginTLS =
777 getOrInsertGlobal(M, "__msan_param_origin_tls",
778 ArrayType::get(OriginTy, kParamTLSSize / 4));
779
780 VAArgTLS =
781 getOrInsertGlobal(M, "__msan_va_arg_tls",
782 ArrayType::get(IRB.getInt64Ty(), kParamTLSSize / 8));
783
784 VAArgOriginTLS =
785 getOrInsertGlobal(M, "__msan_va_arg_origin_tls",
786 ArrayType::get(OriginTy, kParamTLSSize / 4));
787
788 VAArgOverflowSizeTLS = getOrInsertGlobal(M, "__msan_va_arg_overflow_size_tls",
789 IRB.getIntPtrTy(M.getDataLayout()));
790
791 for (size_t AccessSizeIndex = 0; AccessSizeIndex < kNumberOfAccessSizes;
792 AccessSizeIndex++) {
793 unsigned AccessSize = 1 << AccessSizeIndex;
794 std::string FunctionName = "__msan_maybe_warning_" + itostr(AccessSize);
795 MaybeWarningFn[AccessSizeIndex] = M.getOrInsertFunction(
796 FunctionName, TLI.getAttrList(C, {0, 1}, /*Signed=*/false),
797 IRB.getVoidTy(), IRB.getIntNTy(AccessSize * 8), IRB.getInt32Ty());
798 MaybeWarningVarSizeFn = M.getOrInsertFunction(
799 "__msan_maybe_warning_N", TLI.getAttrList(C, {}, /*Signed=*/false),
800 IRB.getVoidTy(), PtrTy, IRB.getInt64Ty(), IRB.getInt32Ty());
801 FunctionName = "__msan_maybe_store_origin_" + itostr(AccessSize);
802 MaybeStoreOriginFn[AccessSizeIndex] = M.getOrInsertFunction(
803 FunctionName, TLI.getAttrList(C, {0, 2}, /*Signed=*/false),
804 IRB.getVoidTy(), IRB.getIntNTy(AccessSize * 8), PtrTy,
805 IRB.getInt32Ty());
806 }
807
808 MsanSetAllocaOriginWithDescriptionFn =
809 M.getOrInsertFunction("__msan_set_alloca_origin_with_descr",
810 IRB.getVoidTy(), PtrTy, IntptrTy, PtrTy, PtrTy);
811 MsanSetAllocaOriginNoDescriptionFn =
812 M.getOrInsertFunction("__msan_set_alloca_origin_no_descr",
813 IRB.getVoidTy(), PtrTy, IntptrTy, PtrTy);
814 MsanPoisonStackFn = M.getOrInsertFunction("__msan_poison_stack",
815 IRB.getVoidTy(), PtrTy, IntptrTy);
816}
817
818/// Insert extern declaration of runtime-provided functions and globals.
819void MemorySanitizer::initializeCallbacks(Module &M,
820 const TargetLibraryInfo &TLI) {
821 // Only do this once.
822 if (CallbacksInitialized)
823 return;
824
825 IRBuilder<> IRB(M);
826 // Initialize callbacks that are common for kernel and userspace
827 // instrumentation.
828 MsanChainOriginFn = M.getOrInsertFunction(
829 "__msan_chain_origin",
830 TLI.getAttrList(C, {0}, /*Signed=*/false, /*Ret=*/true), IRB.getInt32Ty(),
831 IRB.getInt32Ty());
832 MsanSetOriginFn = M.getOrInsertFunction(
833 "__msan_set_origin", TLI.getAttrList(C, {2}, /*Signed=*/false),
834 IRB.getVoidTy(), PtrTy, IntptrTy, IRB.getInt32Ty());
835 MemmoveFn =
836 M.getOrInsertFunction("__msan_memmove", PtrTy, PtrTy, PtrTy, IntptrTy);
837 MemcpyFn =
838 M.getOrInsertFunction("__msan_memcpy", PtrTy, PtrTy, PtrTy, IntptrTy);
839 MemsetFn = M.getOrInsertFunction("__msan_memset",
840 TLI.getAttrList(C, {1}, /*Signed=*/true),
841 PtrTy, PtrTy, IRB.getInt32Ty(), IntptrTy);
842
843 MsanInstrumentAsmStoreFn = M.getOrInsertFunction(
844 "__msan_instrument_asm_store", IRB.getVoidTy(), PtrTy, IntptrTy);
845
846 if (CompileKernel) {
847 createKernelApi(M, TLI);
848 } else {
849 createUserspaceApi(M, TLI);
850 }
851 CallbacksInitialized = true;
852}
853
854FunctionCallee MemorySanitizer::getKmsanShadowOriginAccessFn(bool isStore,
855 int size) {
856 FunctionCallee *Fns =
857 isStore ? MsanMetadataPtrForStore_1_8 : MsanMetadataPtrForLoad_1_8;
858 switch (size) {
859 case 1:
860 return Fns[0];
861 case 2:
862 return Fns[1];
863 case 4:
864 return Fns[2];
865 case 8:
866 return Fns[3];
867 default:
868 return nullptr;
869 }
870}
871
872/// Module-level initialization.
873///
874/// inserts a call to __msan_init to the module's constructor list.
875void MemorySanitizer::initializeModule(Module &M) {
876 auto &DL = M.getDataLayout();
877
878 TargetTriple = M.getTargetTriple();
879
880 bool ShadowPassed = Opts.msan_shadow_base.has_value();
881 bool OriginPassed = Opts.msan_origin_base.has_value();
882 // Check the overrides first
883 if (ShadowPassed || OriginPassed) {
884 CustomMapParams.AndMask = Opts.msan_and_mask;
885 CustomMapParams.XorMask = Opts.msan_xor_mask;
886 CustomMapParams.ShadowBase = Opts.msan_shadow_base.value_or(0);
887 CustomMapParams.OriginBase = Opts.msan_origin_base.value_or(0);
888 MapParams = &CustomMapParams;
889 } else {
890 switch (TargetTriple.getOS()) {
891 case Triple::FreeBSD:
892 switch (TargetTriple.getArch()) {
893 case Triple::aarch64:
894 MapParams = FreeBSD_ARM_MemoryMapParams.bits64;
895 break;
896 case Triple::x86_64:
897 MapParams = FreeBSD_X86_MemoryMapParams.bits64;
898 break;
899 case Triple::x86:
900 MapParams = FreeBSD_X86_MemoryMapParams.bits32;
901 break;
902 default:
903 report_fatal_error("unsupported architecture");
904 }
905 break;
906 case Triple::NetBSD:
907 switch (TargetTriple.getArch()) {
908 case Triple::x86_64:
909 MapParams = NetBSD_X86_MemoryMapParams.bits64;
910 break;
911 default:
912 report_fatal_error("unsupported architecture");
913 }
914 break;
915 case Triple::Linux:
916 switch (TargetTriple.getArch()) {
917 case Triple::x86_64:
918 MapParams = Linux_X86_MemoryMapParams.bits64;
919 break;
920 case Triple::x86:
921 MapParams = Linux_X86_MemoryMapParams.bits32;
922 break;
923 case Triple::mips64:
924 case Triple::mips64el:
925 MapParams = Linux_MIPS_MemoryMapParams.bits64;
926 break;
927 case Triple::ppc64:
928 case Triple::ppc64le:
929 MapParams = Linux_PowerPC_MemoryMapParams.bits64;
930 break;
931 case Triple::systemz:
932 MapParams = Linux_S390_MemoryMapParams.bits64;
933 break;
934 case Triple::aarch64:
936 MapParams = Linux_ARM_MemoryMapParams.bits64;
937 break;
939 MapParams = Linux_LoongArch_MemoryMapParams.bits64;
940 break;
941 case Triple::hexagon:
942 MapParams = Linux_Hexagon_MemoryMapParams_P.bits32;
943 break;
944 default:
945 report_fatal_error("unsupported architecture");
946 }
947 break;
948 default:
949 report_fatal_error("unsupported operating system");
950 }
951 }
952
953 C = &(M.getContext());
954 IRBuilder<> IRB(M);
955 IntptrTy = IRB.getIntPtrTy(DL);
956 OriginTy = IRB.getInt32Ty();
957 PtrTy = IRB.getPtrTy();
958
959 ColdCallWeights = MDBuilder(*C).createUnlikelyBranchWeights();
960 OriginStoreWeights = MDBuilder(*C).createUnlikelyBranchWeights();
961
962 if (!CompileKernel) {
963 if (TrackOrigins)
964 M.getOrInsertGlobal("__msan_track_origins", IRB.getInt32Ty(), [&] {
965 return new GlobalVariable(
966 M, IRB.getInt32Ty(), true, GlobalValue::WeakODRLinkage,
967 IRB.getInt32(TrackOrigins), "__msan_track_origins");
968 });
969
970 if (Recover)
971 M.getOrInsertGlobal("__msan_keep_going", IRB.getInt32Ty(), [&] {
972 return new GlobalVariable(M, IRB.getInt32Ty(), true,
973 GlobalValue::WeakODRLinkage,
974 IRB.getInt32(Recover), "__msan_keep_going");
975 });
976 }
977}
978
979namespace {
980
981/// A helper class that handles instrumentation of VarArg
982/// functions on a particular platform.
983///
984/// Implementations are expected to insert the instrumentation
985/// necessary to propagate argument shadow through VarArg function
986/// calls. Visit* methods are called during an InstVisitor pass over
987/// the function, and should avoid creating new basic blocks. A new
988/// instance of this class is created for each instrumented function.
989struct VarArgHelper {
990 virtual ~VarArgHelper() = default;
991
992 /// Visit a CallBase.
993 virtual void visitCallBase(CallBase &CB, IRBuilder<> &IRB) = 0;
994
995 /// Visit a va_start call.
996 virtual void visitVAStartInst(VAStartInst &I) = 0;
997
998 /// Visit a va_copy call.
999 virtual void visitVACopyInst(VACopyInst &I) = 0;
1000
1001 /// Finalize function instrumentation.
1002 ///
1003 /// This method is called after visiting all interesting (see above)
1004 /// instructions in a function.
1005 virtual void finalizeInstrumentation() = 0;
1006};
1007
1008struct MemorySanitizerVisitor;
1009
1010} // end anonymous namespace
1011
1012static VarArgHelper *CreateVarArgHelper(Function &Func, MemorySanitizer &Msan,
1013 MemorySanitizerVisitor &Visitor);
1014
1015static unsigned TypeSizeToSizeIndex(TypeSize TS) {
1016 if (TS.isScalable())
1017 // Scalable types unconditionally take slowpaths.
1018 return kNumberOfAccessSizes;
1019 unsigned TypeSizeFixed = TS.getFixedValue();
1020 if (TypeSizeFixed <= 8)
1021 return 0;
1022 return Log2_32_Ceil((TypeSizeFixed + 7) / 8);
1023}
1024
1025namespace {
1026
1027/// Helper class to attach debug information of the given instruction onto new
1028/// instructions inserted after.
1029class NextNodeIRBuilder : public IRBuilder<> {
1030public:
1031 explicit NextNodeIRBuilder(Instruction *IP) : IRBuilder<>(IP->getNextNode()) {
1032 SetCurrentDebugLocation(IP->getDebugLoc());
1033 }
1034};
1035
1036/// This class does all the work for a given function. Store and Load
1037/// instructions store and load corresponding shadow and origin
1038/// values. Most instructions propagate shadow from arguments to their
1039/// return values. Certain instructions (most importantly, BranchInst)
1040/// test their argument shadow and print reports (with a runtime call) if it's
1041/// non-zero.
1042struct MemorySanitizerVisitor : public InstVisitor<MemorySanitizerVisitor> {
1043 const InstrumentationOptions &Opts;
1044 Function &F;
1045 MemorySanitizer &MS;
1046 SmallVector<PHINode *, 16> ShadowPHINodes;
1047 ValueMap<Value *, Value *> ShadowMap, OriginMap;
1048 std::unique_ptr<VarArgHelper> VAHelper;
1049 const TargetLibraryInfo *TLI;
1050 Instruction *FnPrologueEnd;
1051 SmallVector<Instruction *, 16> Instructions;
1052
1053 // The following flags disable parts of MSan instrumentation based on
1054 // exclusion list contents and command-line options.
1055 bool InsertChecks;
1056 bool PropagateShadow;
1057 bool PoisonStack;
1058 bool PoisonUndef;
1059 bool PoisonUndefVectors;
1060
1061 struct ShadowOriginAndInsertPoint {
1062 Value *Shadow;
1063 Value *Origin;
1064 Instruction *OrigIns;
1065
1066 ShadowOriginAndInsertPoint(Value *S, Value *O, Instruction *I)
1067 : Shadow(S), Origin(O), OrigIns(I) {}
1068 };
1070 DenseMap<const DILocation *, int> LazyWarningDebugLocationCount;
1071 SmallSetVector<AllocaInst *, 16> AllocaSet;
1074 int64_t SplittableBlocksCount = 0;
1075
1076 MemorySanitizerVisitor(Function &F, MemorySanitizer &MS,
1077 const TargetLibraryInfo &TLI)
1078 : Opts(MS.Opts), F(F), MS(MS), VAHelper(CreateVarArgHelper(F, MS, *this)),
1079 TLI(&TLI) {
1080 bool SanitizeFunction = F.hasFnAttribute(Attribute::SanitizeMemory) &&
1081 !Opts.msan_disable_checks;
1082 InsertChecks = SanitizeFunction;
1083 PropagateShadow = SanitizeFunction;
1084 PoisonStack = SanitizeFunction && Opts.msan_poison_stack;
1085 PoisonUndef = SanitizeFunction && Opts.msan_poison_undef;
1086 PoisonUndefVectors = SanitizeFunction && Opts.msan_poison_undef_vectors;
1087
1088 // In the presence of unreachable blocks, we may see Phi nodes with
1089 // incoming nodes from such blocks. Since InstVisitor skips unreachable
1090 // blocks, such nodes will not have any shadow value associated with them.
1091 // It's easier to remove unreachable blocks than deal with missing shadow.
1093
1094 MS.initializeCallbacks(*F.getParent(), TLI);
1095 FnPrologueEnd =
1096 IRBuilder<>(F.getEntryBlock().getFirstNonPHIIt())
1097 .CreateIntrinsicWithoutFolding(Intrinsic::donothing, {});
1098
1099 if (MS.CompileKernel) {
1100 IRBuilder<> IRB(FnPrologueEnd);
1101 insertKmsanPrologue(IRB);
1102 }
1103
1104 LLVM_DEBUG(if (!InsertChecks) dbgs()
1105 << "MemorySanitizer is not inserting checks into '"
1106 << F.getName() << "'\n");
1107 }
1108
1109 bool instrumentWithCalls(Value *V) {
1110 // Constants likely will be eliminated by follow-up passes.
1111 if (isa<Constant>(V))
1112 return false;
1113 ++SplittableBlocksCount;
1114 return Opts.msan_instrumentation_with_call_threshold >= 0 &&
1115 SplittableBlocksCount >
1116 Opts.msan_instrumentation_with_call_threshold;
1117 }
1118
1119 bool isInPrologue(Instruction &I) {
1120 return I.getParent() == FnPrologueEnd->getParent() &&
1121 (&I == FnPrologueEnd || I.comesBefore(FnPrologueEnd));
1122 }
1123
1124 // Creates a new origin and records the stack trace. In general we can call
1125 // this function for any origin manipulation we like. However it will cost
1126 // runtime resources. So use this wisely only if it can provide additional
1127 // information helpful to a user.
1128 Value *updateOrigin(Value *V, IRBuilder<> &IRB) {
1129 if (MS.TrackOrigins <= 1)
1130 return V;
1131 return IRB.CreateCall(MS.MsanChainOriginFn, V);
1132 }
1133
1134 Value *originToIntptr(IRBuilder<> &IRB, Value *Origin) {
1135 const DataLayout &DL = F.getDataLayout();
1136 unsigned IntptrSize = DL.getTypeStoreSize(MS.IntptrTy);
1137 if (IntptrSize == kOriginSize)
1138 return Origin;
1139 assert(IntptrSize == kOriginSize * 2);
1140 Origin = IRB.CreateIntCast(Origin, MS.IntptrTy, /* isSigned */ false);
1141 return IRB.CreateOr(Origin, IRB.CreateShl(Origin, kOriginSize * 8));
1142 }
1143
1144 /// Fill memory range with the given origin value.
1145 void paintOrigin(IRBuilder<> &IRB, Value *Origin, Value *OriginPtr,
1146 TypeSize TS, Align Alignment) {
1147 const DataLayout &DL = F.getDataLayout();
1148 const Align IntptrAlignment = DL.getABITypeAlign(MS.IntptrTy);
1149 unsigned IntptrSize = DL.getTypeStoreSize(MS.IntptrTy);
1150 assert(IntptrAlignment >= kMinOriginAlignment);
1151 assert(IntptrSize >= kOriginSize);
1152
1153 // Note: The loop based formation works for fixed length vectors too,
1154 // however we prefer to unroll and specialize alignment below.
1155 if (TS.isScalable()) {
1156 Value *Size = IRB.CreateTypeSize(MS.IntptrTy, TS);
1157 Value *RoundUp =
1158 IRB.CreateAdd(Size, ConstantInt::get(MS.IntptrTy, kOriginSize - 1));
1159 Value *End =
1160 IRB.CreateUDiv(RoundUp, ConstantInt::get(MS.IntptrTy, kOriginSize));
1161 auto [InsertPt, Index] =
1164
1165 Value *GEP = IRB.CreateGEP(MS.OriginTy, OriginPtr, Index);
1167 return;
1168 }
1169
1170 unsigned Size = TS.getFixedValue();
1171
1172 unsigned Ofs = 0;
1173 Align CurrentAlignment = Alignment;
1174 if (Alignment >= IntptrAlignment && IntptrSize > kOriginSize) {
1175 Value *IntptrOrigin = originToIntptr(IRB, Origin);
1176 Value *IntptrOriginPtr = IRB.CreatePointerCast(OriginPtr, MS.PtrTy);
1177 for (unsigned i = 0; i < Size / IntptrSize; ++i) {
1178 Value *Ptr = i ? IRB.CreateConstGEP1_32(MS.IntptrTy, IntptrOriginPtr, i)
1179 : IntptrOriginPtr;
1180 IRB.CreateAlignedStore(IntptrOrigin, Ptr, CurrentAlignment);
1181 Ofs += IntptrSize / kOriginSize;
1182 CurrentAlignment = IntptrAlignment;
1183 }
1184 }
1185
1186 for (unsigned i = Ofs; i < (Size + kOriginSize - 1) / kOriginSize; ++i) {
1187 Value *GEP =
1188 i ? IRB.CreateConstGEP1_32(MS.OriginTy, OriginPtr, i) : OriginPtr;
1189 IRB.CreateAlignedStore(Origin, GEP, CurrentAlignment);
1190 CurrentAlignment = kMinOriginAlignment;
1191 }
1192 }
1193
1194 void storeOrigin(IRBuilder<> &IRB, Value *Addr, Value *Shadow, Value *Origin,
1195 Value *OriginPtr, Align Alignment) {
1196 const DataLayout &DL = F.getDataLayout();
1197 const Align OriginAlignment = std::max(kMinOriginAlignment, Alignment);
1198 TypeSize StoreSize = DL.getTypeStoreSize(Shadow->getType());
1199 // ZExt cannot convert between vector and scalar
1200 Value *ConvertedShadow = convertShadowToScalar(Shadow, IRB);
1201 if (auto *ConstantShadow = dyn_cast<Constant>(ConvertedShadow)) {
1202 if (!Opts.msan_check_constant_shadow || ConstantShadow->isNullValue()) {
1203 // Origin is not needed: value is initialized or const shadow is
1204 // ignored.
1205 return;
1206 }
1207 if (llvm::isKnownNonZero(ConvertedShadow, DL)) {
1208 // Copy origin as the value is definitely uninitialized.
1209 paintOrigin(IRB, updateOrigin(Origin, IRB), OriginPtr, StoreSize,
1210 OriginAlignment);
1211 return;
1212 }
1213 // Fallback to runtime check, which still can be optimized out later.
1214 }
1215
1216 TypeSize TypeSizeInBits = DL.getTypeSizeInBits(ConvertedShadow->getType());
1217 unsigned SizeIndex = TypeSizeToSizeIndex(TypeSizeInBits);
1218 if (instrumentWithCalls(ConvertedShadow) &&
1219 SizeIndex < kNumberOfAccessSizes && !MS.CompileKernel) {
1220 FunctionCallee Fn = MS.MaybeStoreOriginFn[SizeIndex];
1221 Value *ConvertedShadow2 =
1222 IRB.CreateZExt(ConvertedShadow, IRB.getIntNTy(8 * (1 << SizeIndex)));
1223 CallBase *CB = IRB.CreateCall(Fn, {ConvertedShadow2, Addr, Origin});
1224 CB->addParamAttr(0, Attribute::ZExt);
1225 CB->addParamAttr(2, Attribute::ZExt);
1226 } else {
1227 Value *Cmp = convertToBool(ConvertedShadow, IRB, "_mscmp");
1229 Cmp, &*IRB.GetInsertPoint(), false, MS.OriginStoreWeights);
1230 IRBuilder<> IRBNew(CheckTerm);
1231 paintOrigin(IRBNew, updateOrigin(Origin, IRBNew), OriginPtr, StoreSize,
1232 OriginAlignment);
1233 }
1234 }
1235
1236 void materializeStores() {
1237 for (StoreInst *SI : StoreList) {
1238 IRBuilder<> IRB(SI);
1239 Value *Val = SI->getValueOperand();
1240 Value *Addr = SI->getPointerOperand();
1241 // No shadow for memory in untracked address spaces (see visitStoreInst).
1242 if (isUntrackedAddrSpace(Addr))
1243 continue;
1244 Value *Shadow = SI->isAtomic() ? getCleanShadow(Val) : getShadow(Val);
1245 Value *ShadowPtr, *OriginPtr;
1246 Type *ShadowTy = Shadow->getType();
1247 const Align Alignment = SI->getAlign();
1248 const Align OriginAlignment = std::max(kMinOriginAlignment, Alignment);
1249 std::tie(ShadowPtr, OriginPtr) =
1250 getShadowOriginPtr(Addr, IRB, ShadowTy, Alignment, /*isStore*/ true);
1251
1252 [[maybe_unused]] StoreInst *NewSI =
1253 IRB.CreateAlignedStore(Shadow, ShadowPtr, Alignment);
1254 LLVM_DEBUG(dbgs() << " STORE: " << *NewSI << "\n");
1255
1256 if (SI->isAtomic())
1257 SI->setOrdering(addReleaseOrdering(SI->getOrdering()));
1258
1259 if (MS.TrackOrigins && !SI->isAtomic())
1260 storeOrigin(IRB, Addr, Shadow, getOrigin(Val), OriginPtr,
1261 OriginAlignment);
1262 }
1263 }
1264
1265 // Returns true if Debug Location corresponds to multiple warnings.
1266 bool shouldDisambiguateWarningLocation(const DebugLoc &DebugLoc) {
1267 if (MS.TrackOrigins < 2)
1268 return false;
1269
1270 if (LazyWarningDebugLocationCount.empty())
1271 for (const auto &I : InstrumentationList)
1272 ++LazyWarningDebugLocationCount[I.OrigIns->getDebugLoc()];
1273
1274 return LazyWarningDebugLocationCount[DebugLoc] >=
1275 Opts.msan_disambiguate_warning_threshold;
1276 }
1277
1278 /// Helper function to insert a warning at IRB's current insert point.
1279 void insertWarningFn(IRBuilder<> &IRB, Value *Origin) {
1280 if (!Origin)
1281 Origin = (Value *)IRB.getInt32(0);
1282 assert(Origin->getType()->isIntegerTy());
1283
1284 if (shouldDisambiguateWarningLocation(IRB.getCurrentDebugLocation())) {
1285 // Try to create additional origin with debug info of the last origin
1286 // instruction. It may provide additional information to the user.
1287 if (Instruction *OI = dyn_cast_or_null<Instruction>(Origin)) {
1288 assert(MS.TrackOrigins);
1289 auto NewDebugLoc = OI->getDebugLoc();
1290 // Origin update with missing or the same debug location provides no
1291 // additional value.
1292 if (NewDebugLoc && NewDebugLoc != IRB.getCurrentDebugLocation()) {
1293 // Insert update just before the check, so we call runtime only just
1294 // before the report.
1295 IRBuilder<> IRBOrigin(&*IRB.GetInsertPoint());
1296 IRBOrigin.SetCurrentDebugLocation(NewDebugLoc);
1297 Origin = updateOrigin(Origin, IRBOrigin);
1298 }
1299 }
1300 }
1301
1302 if (MS.CompileKernel || MS.TrackOrigins)
1303 IRB.CreateCall(MS.WarningFn, Origin)->setCannotMerge();
1304 else
1305 IRB.CreateCall(MS.WarningFn)->setCannotMerge();
1306 // FIXME: Insert UnreachableInst if !MS.Recover?
1307 // This may invalidate some of the following checks and needs to be done
1308 // at the very end.
1309 }
1310
1311 void materializeOneCheck(IRBuilder<> &IRB, Value *ConvertedShadow,
1312 Value *Origin) {
1313 const DataLayout &DL = F.getDataLayout();
1314 TypeSize TypeSizeInBits = DL.getTypeSizeInBits(ConvertedShadow->getType());
1315 unsigned SizeIndex = TypeSizeToSizeIndex(TypeSizeInBits);
1316 if (instrumentWithCalls(ConvertedShadow) && !MS.CompileKernel) {
1317 // ZExt cannot convert between vector and scalar
1318 ConvertedShadow = convertShadowToScalar(ConvertedShadow, IRB);
1319 Value *ConvertedShadow2 =
1320 IRB.CreateZExt(ConvertedShadow, IRB.getIntNTy(8 * (1 << SizeIndex)));
1321
1322 if (SizeIndex < kNumberOfAccessSizes) {
1323 FunctionCallee Fn = MS.MaybeWarningFn[SizeIndex];
1324 CallBase *CB = IRB.CreateCall(
1325 Fn,
1326 {ConvertedShadow2,
1327 MS.TrackOrigins && Origin ? Origin : (Value *)IRB.getInt32(0)});
1328 CB->addParamAttr(0, Attribute::ZExt);
1329 CB->addParamAttr(1, Attribute::ZExt);
1330 } else {
1331 FunctionCallee Fn = MS.MaybeWarningVarSizeFn;
1332 Value *ShadowAlloca = IRB.CreateAlloca(ConvertedShadow2->getType(), 0u);
1333 IRB.CreateStore(ConvertedShadow2, ShadowAlloca);
1334 unsigned ShadowSize = DL.getTypeAllocSize(ConvertedShadow2->getType());
1335 CallBase *CB = IRB.CreateCall(
1336 Fn,
1337 {ShadowAlloca, ConstantInt::get(IRB.getInt64Ty(), ShadowSize),
1338 MS.TrackOrigins && Origin ? Origin : (Value *)IRB.getInt32(0)});
1339 CB->addParamAttr(1, Attribute::ZExt);
1340 CB->addParamAttr(2, Attribute::ZExt);
1341 }
1342 } else {
1343 Value *Cmp = convertToBool(ConvertedShadow, IRB, "_mscmp");
1345 Cmp, &*IRB.GetInsertPoint(),
1346 /* Unreachable */ !MS.Recover, MS.ColdCallWeights);
1347
1348 IRB.SetInsertPoint(CheckTerm);
1349 insertWarningFn(IRB, Origin);
1350 LLVM_DEBUG(dbgs() << " CHECK: " << *Cmp << "\n");
1351 }
1352 }
1353
1354 void materializeInstructionChecks(
1355 ArrayRef<ShadowOriginAndInsertPoint> InstructionChecks) {
1356 const DataLayout &DL = F.getDataLayout();
1357 // Disable combining in some cases. TrackOrigins checks each shadow to pick
1358 // correct origin.
1359 bool Combine = !MS.TrackOrigins;
1360 Instruction *Instruction = InstructionChecks.front().OrigIns;
1361 Value *Shadow = nullptr;
1362 for (const auto &ShadowData : InstructionChecks) {
1363 assert(ShadowData.OrigIns == Instruction);
1364 IRBuilder<> IRB(Instruction);
1365
1366 Value *ConvertedShadow = ShadowData.Shadow;
1367
1368 if (auto *ConstantShadow = dyn_cast<Constant>(ConvertedShadow)) {
1369 if (!Opts.msan_check_constant_shadow || ConstantShadow->isNullValue()) {
1370 // Skip, value is initialized or const shadow is ignored.
1371 continue;
1372 }
1373 if (llvm::isKnownNonZero(ConvertedShadow, DL)) {
1374 // Report as the value is definitely uninitialized.
1375 insertWarningFn(IRB, ShadowData.Origin);
1376 if (!MS.Recover)
1377 return; // Always fail and stop here, not need to check the rest.
1378 // Skip entire instruction,
1379 continue;
1380 }
1381 // Fallback to runtime check, which still can be optimized out later.
1382 }
1383
1384 if (!Combine) {
1385 materializeOneCheck(IRB, ConvertedShadow, ShadowData.Origin);
1386 continue;
1387 }
1388
1389 if (!Shadow) {
1390 Shadow = ConvertedShadow;
1391 continue;
1392 }
1393
1394 Shadow = convertToBool(Shadow, IRB, "_mscmp");
1395 ConvertedShadow = convertToBool(ConvertedShadow, IRB, "_mscmp");
1396 Shadow = IRB.CreateOr(Shadow, ConvertedShadow, "_msor");
1397 }
1398
1399 if (Shadow) {
1400 assert(Combine);
1401 IRBuilder<> IRB(Instruction);
1402 materializeOneCheck(IRB, Shadow, nullptr);
1403 }
1404 }
1405
1406 static bool isAArch64SVCount(Type *Ty) {
1407 if (TargetExtType *TTy = dyn_cast<TargetExtType>(Ty))
1408 return TTy->getName() == "aarch64.svcount";
1409 return false;
1410 }
1411
1412 // This is intended to match the "AArch64 Predicate-as-Counter Type" (aka
1413 // 'target("aarch64.svcount")', but not e.g., <vscale x 4 x i32>.
1414 static bool isScalableNonVectorType(Type *Ty) {
1415 if (!isAArch64SVCount(Ty))
1416 LLVM_DEBUG(dbgs() << "isScalableNonVectorType: Unexpected type " << *Ty
1417 << "\n");
1418
1419 return Ty->isScalableTy() && !isa<VectorType>(Ty);
1420 }
1421
1422 void materializeChecks() {
1423#ifndef NDEBUG
1424 // For assert below.
1425 SmallPtrSet<Instruction *, 16> Done;
1426#endif
1427
1428 for (auto I = InstrumentationList.begin();
1429 I != InstrumentationList.end();) {
1430 auto OrigIns = I->OrigIns;
1431 // Checks are grouped by the original instruction. We call all
1432 // `insertShadowCheck` for an instruction at once.
1433 assert(Done.insert(OrigIns).second);
1434 auto J = std::find_if(I + 1, InstrumentationList.end(),
1435 [OrigIns](const ShadowOriginAndInsertPoint &R) {
1436 return OrigIns != R.OrigIns;
1437 });
1438 // Process all checks of instruction at once.
1439 materializeInstructionChecks(ArrayRef<ShadowOriginAndInsertPoint>(I, J));
1440 I = J;
1441 }
1442
1443 LLVM_DEBUG(dbgs() << "DONE:\n" << F);
1444 }
1445
1446 // Returns the last instruction in the new prologue
1447 void insertKmsanPrologue(IRBuilder<> &IRB) {
1448 Value *ContextState = IRB.CreateCall(MS.MsanGetContextStateFn, {});
1449 Constant *Zero = IRB.getInt32(0);
1450 MS.ParamTLS = IRB.CreateGEP(MS.MsanContextStateTy, ContextState,
1451 {Zero, IRB.getInt32(0)}, "param_shadow");
1452 MS.RetvalTLS = IRB.CreateGEP(MS.MsanContextStateTy, ContextState,
1453 {Zero, IRB.getInt32(1)}, "retval_shadow");
1454 MS.VAArgTLS = IRB.CreateGEP(MS.MsanContextStateTy, ContextState,
1455 {Zero, IRB.getInt32(2)}, "va_arg_shadow");
1456 MS.VAArgOriginTLS = IRB.CreateGEP(MS.MsanContextStateTy, ContextState,
1457 {Zero, IRB.getInt32(3)}, "va_arg_origin");
1458 MS.VAArgOverflowSizeTLS =
1459 IRB.CreateGEP(MS.MsanContextStateTy, ContextState,
1460 {Zero, IRB.getInt32(4)}, "va_arg_overflow_size");
1461 MS.ParamOriginTLS = IRB.CreateGEP(MS.MsanContextStateTy, ContextState,
1462 {Zero, IRB.getInt32(5)}, "param_origin");
1463 MS.RetvalOriginTLS =
1464 IRB.CreateGEP(MS.MsanContextStateTy, ContextState,
1465 {Zero, IRB.getInt32(6)}, "retval_origin");
1466 if (MS.TargetTriple.getArch() == Triple::systemz)
1467 MS.MsanMetadataAlloca = IRB.CreateAlloca(MS.MsanMetadata, 0u);
1468 }
1469
1470 /// Add MemorySanitizer instrumentation to a function.
1471 bool runOnFunction() {
1472 // Iterate all BBs in depth-first order and create shadow instructions
1473 // for all instructions (where applicable).
1474 // For PHI nodes we create dummy shadow PHIs which will be finalized later.
1475 for (BasicBlock *BB : depth_first(FnPrologueEnd->getParent()))
1476 visit(*BB);
1477
1478 // `visit` above only collects instructions. Process them after iterating
1479 // CFG to avoid requirement on CFG transformations.
1480 for (Instruction *I : Instructions)
1482
1483 // Finalize PHI nodes.
1484 for (PHINode *PN : ShadowPHINodes) {
1485 PHINode *PNS = cast<PHINode>(getShadow(PN));
1486 PHINode *PNO = MS.TrackOrigins ? cast<PHINode>(getOrigin(PN)) : nullptr;
1487 size_t NumValues = PN->getNumIncomingValues();
1488 for (size_t v = 0; v < NumValues; v++) {
1489 PNS->addIncoming(getShadow(PN, v), PN->getIncomingBlock(v));
1490 if (PNO)
1491 PNO->addIncoming(getOrigin(PN, v), PN->getIncomingBlock(v));
1492 }
1493 }
1494
1495 VAHelper->finalizeInstrumentation();
1496
1497 // Poison llvm.lifetime.start intrinsics, if we haven't fallen back to
1498 // instrumenting only allocas.
1499 if (Opts.msan_handle_lifetime_intrinsics) {
1500 for (auto Item : LifetimeStartList) {
1501 instrumentAlloca(*Item.second, Item.first);
1502 AllocaSet.remove(Item.second);
1503 }
1504 }
1505 // Poison the allocas for which we didn't instrument the corresponding
1506 // lifetime intrinsics.
1507 for (AllocaInst *AI : AllocaSet)
1508 instrumentAlloca(*AI);
1509
1510 // Insert shadow value checks.
1511 materializeChecks();
1512
1513 // Delayed instrumentation of StoreInst.
1514 // This may not add new address checks.
1515 materializeStores();
1516
1517 return true;
1518 }
1519
1520 /// Compute the shadow type that corresponds to a given Value.
1521 Type *getShadowTy(Value *V) { return getShadowTy(V->getType()); }
1522
1523 /// Compute the shadow type that corresponds to a given Type.
1524 Type *getShadowTy(Type *OrigTy) {
1525 if (!OrigTy->isSized()) {
1526 return nullptr;
1527 }
1528 // For integer type, shadow is the same as the original type.
1529 // This may return weird-sized types like i1.
1530 if (IntegerType *IT = dyn_cast<IntegerType>(OrigTy))
1531 return IT;
1532 const DataLayout &DL = F.getDataLayout();
1533 if (VectorType *VT = dyn_cast<VectorType>(OrigTy)) {
1534 uint32_t EltSize = DL.getTypeSizeInBits(VT->getElementType());
1535 return VectorType::get(IntegerType::get(*MS.C, EltSize),
1536 VT->getElementCount());
1537 }
1538 if (ArrayType *AT = dyn_cast<ArrayType>(OrigTy)) {
1539 return ArrayType::get(getShadowTy(AT->getElementType()),
1540 AT->getNumElements());
1541 }
1542 if (StructType *ST = dyn_cast<StructType>(OrigTy)) {
1544 for (unsigned i = 0, n = ST->getNumElements(); i < n; i++)
1545 Elements.push_back(getShadowTy(ST->getElementType(i)));
1546 StructType *Res = StructType::get(*MS.C, Elements, ST->isPacked());
1547 LLVM_DEBUG(dbgs() << "getShadowTy: " << *ST << " ===> " << *Res << "\n");
1548 return Res;
1549 }
1550 if (isScalableNonVectorType(OrigTy)) {
1551 LLVM_DEBUG(dbgs() << "getShadowTy: Scalable non-vector type: " << *OrigTy
1552 << "\n");
1553 return OrigTy;
1554 }
1555
1556 uint32_t TypeSize = DL.getTypeSizeInBits(OrigTy);
1557 return IntegerType::get(*MS.C, TypeSize);
1558 }
1559
1560 /// Extract combined shadow of struct elements as a bool
1561 Value *collapseStructShadow(StructType *Struct, Value *Shadow,
1562 IRBuilder<> &IRB) {
1563 Value *FalseVal = IRB.getIntN(/* width */ 1, /* value */ 0);
1564 Value *Aggregator = FalseVal;
1565
1566 for (unsigned Idx = 0; Idx < Struct->getNumElements(); Idx++) {
1567 // Combine by ORing together each element's bool shadow
1568 Value *ShadowItem = IRB.CreateExtractValue(Shadow, Idx);
1569 Value *ShadowBool = convertToBool(ShadowItem, IRB);
1570
1571 if (Aggregator != FalseVal)
1572 Aggregator = IRB.CreateOr(Aggregator, ShadowBool);
1573 else
1574 Aggregator = ShadowBool;
1575 }
1576
1577 return Aggregator;
1578 }
1579
1580 // Extract combined shadow of array elements
1581 Value *collapseArrayShadow(ArrayType *Array, Value *Shadow,
1582 IRBuilder<> &IRB) {
1583 if (!Array->getNumElements())
1584 return IRB.getIntN(/* width */ 1, /* value */ 0);
1585
1586 Value *FirstItem = IRB.CreateExtractValue(Shadow, 0);
1587 Value *Aggregator = convertShadowToScalar(FirstItem, IRB);
1588
1589 for (unsigned Idx = 1; Idx < Array->getNumElements(); Idx++) {
1590 Value *ShadowItem = IRB.CreateExtractValue(Shadow, Idx);
1591 Value *ShadowInner = convertShadowToScalar(ShadowItem, IRB);
1592 Aggregator = IRB.CreateOr(Aggregator, ShadowInner);
1593 }
1594 return Aggregator;
1595 }
1596
1597 /// Convert a shadow value to it's flattened variant. The resulting
1598 /// shadow may not necessarily have the same bit width as the input
1599 /// value, but it will always be comparable to zero.
1600 Value *convertShadowToScalar(Value *V, IRBuilder<> &IRB) {
1601 if (StructType *Struct = dyn_cast<StructType>(V->getType()))
1602 return collapseStructShadow(Struct, V, IRB);
1603 if (ArrayType *Array = dyn_cast<ArrayType>(V->getType()))
1604 return collapseArrayShadow(Array, V, IRB);
1605 if (isa<VectorType>(V->getType())) {
1606 if (isa<ScalableVectorType>(V->getType()))
1607 return convertShadowToScalar(IRB.CreateOrReduce(V), IRB);
1608 unsigned BitWidth =
1609 V->getType()->getPrimitiveSizeInBits().getFixedValue();
1610 return IRB.CreateBitCast(V, IntegerType::get(*MS.C, BitWidth));
1611 }
1612 return V;
1613 }
1614
1615 // Convert a scalar value to an i1 by comparing with 0
1616 Value *convertToBool(Value *V, IRBuilder<> &IRB, const Twine &name = "") {
1617 Type *VTy = V->getType();
1618 if (!VTy->isIntegerTy())
1619 return convertToBool(convertShadowToScalar(V, IRB), IRB, name);
1620 if (VTy->getIntegerBitWidth() == 1)
1621 // Just converting a bool to a bool, so do nothing.
1622 return V;
1623 return IRB.CreateICmpNE(V, ConstantInt::get(VTy, 0), name);
1624 }
1625
1626 Type *ptrToIntPtrType(Type *PtrTy) const {
1627 if (VectorType *VectTy = dyn_cast<VectorType>(PtrTy)) {
1628 return VectorType::get(ptrToIntPtrType(VectTy->getElementType()),
1629 VectTy->getElementCount());
1630 }
1631 assert(PtrTy->isIntOrPtrTy());
1632 return MS.IntptrTy;
1633 }
1634
1635 Type *getPtrToShadowPtrType(Type *IntPtrTy, Type *ShadowTy) const {
1636 if (VectorType *VectTy = dyn_cast<VectorType>(IntPtrTy)) {
1637 return VectorType::get(
1638 getPtrToShadowPtrType(VectTy->getElementType(), ShadowTy),
1639 VectTy->getElementCount());
1640 }
1641 assert(IntPtrTy == MS.IntptrTy);
1642 return MS.PtrTy;
1643 }
1644
1645 Constant *constToIntPtr(Type *IntPtrTy, uint64_t C) const {
1646 if (VectorType *VectTy = dyn_cast<VectorType>(IntPtrTy)) {
1648 VectTy->getElementCount(),
1649 constToIntPtr(VectTy->getElementType(), C));
1650 }
1651 assert(IntPtrTy == MS.IntptrTy);
1652 // TODO: Avoid implicit trunc?
1653 // See https://github.com/llvm/llvm-project/issues/112510.
1654 return ConstantInt::get(MS.IntptrTy, C, /*IsSigned=*/false,
1655 /*ImplicitTrunc=*/true);
1656 }
1657
1658 /// Returns the integer shadow offset that corresponds to a given
1659 /// application address, whereby:
1660 ///
1661 /// Offset = (Addr & ~AndMask) ^ XorMask
1662 /// Shadow = ShadowBase + Offset
1663 /// Origin = (OriginBase + Offset) & ~Alignment
1664 ///
1665 /// Note: for efficiency, many shadow mappings only require use the XorMask
1666 /// and OriginBase; the AndMask and ShadowBase are often zero.
1667 Value *getShadowPtrOffset(Value *Addr, IRBuilder<> &IRB) {
1668 Type *IntptrTy = ptrToIntPtrType(Addr->getType());
1669 Value *OffsetLong = IRB.CreatePointerCast(Addr, IntptrTy);
1670
1671 if (uint64_t AndMask = MS.MapParams->AndMask)
1672 OffsetLong = IRB.CreateAnd(OffsetLong, constToIntPtr(IntptrTy, ~AndMask));
1673
1674 if (uint64_t XorMask = MS.MapParams->XorMask)
1675 OffsetLong = IRB.CreateXor(OffsetLong, constToIntPtr(IntptrTy, XorMask));
1676 return OffsetLong;
1677 }
1678
1679 /// Compute the shadow and origin addresses corresponding to a given
1680 /// application address.
1681 ///
1682 /// Shadow = ShadowBase + Offset
1683 /// Origin = (OriginBase + Offset) & ~3ULL
1684 /// Addr can be a ptr or <N x ptr>. In both cases ShadowTy the shadow type of
1685 /// a single pointee.
1686 /// Returns <shadow_ptr, origin_ptr> or <<N x shadow_ptr>, <N x origin_ptr>>.
1687 std::pair<Value *, Value *>
1688 getShadowOriginPtrUserspace(Value *Addr, IRBuilder<> &IRB, Type *ShadowTy,
1689 MaybeAlign Alignment) {
1690 VectorType *VectTy = dyn_cast<VectorType>(Addr->getType());
1691 if (!VectTy) {
1692 assert(Addr->getType()->isPointerTy());
1693 } else {
1694 assert(VectTy->getElementType()->isPointerTy());
1695 }
1696 Type *IntptrTy = ptrToIntPtrType(Addr->getType());
1697 Value *ShadowOffset = getShadowPtrOffset(Addr, IRB);
1698 Value *ShadowLong = ShadowOffset;
1699 if (uint64_t ShadowBase = MS.MapParams->ShadowBase) {
1700 ShadowLong =
1701 IRB.CreateAdd(ShadowLong, constToIntPtr(IntptrTy, ShadowBase));
1702 }
1703 Value *ShadowPtr = IRB.CreateIntToPtr(
1704 ShadowLong, getPtrToShadowPtrType(IntptrTy, ShadowTy));
1705
1706 Value *OriginPtr = nullptr;
1707 if (MS.TrackOrigins) {
1708 Value *OriginLong = ShadowOffset;
1709 uint64_t OriginBase = MS.MapParams->OriginBase;
1710 if (OriginBase != 0)
1711 OriginLong =
1712 IRB.CreateAdd(OriginLong, constToIntPtr(IntptrTy, OriginBase));
1713 if (!Alignment || *Alignment < kMinOriginAlignment) {
1715 OriginLong = IRB.CreateAnd(OriginLong, constToIntPtr(IntptrTy, ~Mask));
1716 }
1717 OriginPtr = IRB.CreateIntToPtr(
1718 OriginLong, getPtrToShadowPtrType(IntptrTy, MS.OriginTy));
1719 }
1720 return std::make_pair(ShadowPtr, OriginPtr);
1721 }
1722
1723 template <typename... ArgsTy>
1724 Value *createMetadataCall(IRBuilder<> &IRB, FunctionCallee Callee,
1725 ArgsTy... Args) {
1726 if (MS.TargetTriple.getArch() == Triple::systemz) {
1727 IRB.CreateCall(Callee,
1728 {MS.MsanMetadataAlloca, std::forward<ArgsTy>(Args)...});
1729 return IRB.CreateLoad(MS.MsanMetadata, MS.MsanMetadataAlloca);
1730 }
1731
1732 return IRB.CreateCall(Callee, {std::forward<ArgsTy>(Args)...});
1733 }
1734
1735 std::pair<Value *, Value *> getShadowOriginPtrKernelNoVec(Value *Addr,
1736 IRBuilder<> &IRB,
1737 Type *ShadowTy,
1738 bool isStore) {
1739 Value *ShadowOriginPtrs;
1740 const DataLayout &DL = F.getDataLayout();
1741 TypeSize Size = DL.getTypeStoreSize(ShadowTy);
1742
1743 FunctionCallee Getter = MS.getKmsanShadowOriginAccessFn(isStore, Size);
1744 Value *AddrCast = IRB.CreatePointerCast(Addr, MS.PtrTy);
1745 if (Getter) {
1746 ShadowOriginPtrs = createMetadataCall(IRB, Getter, AddrCast);
1747 } else {
1748 Value *SizeVal = ConstantInt::get(MS.IntptrTy, Size);
1749 ShadowOriginPtrs = createMetadataCall(
1750 IRB,
1751 isStore ? MS.MsanMetadataPtrForStoreN : MS.MsanMetadataPtrForLoadN,
1752 AddrCast, SizeVal);
1753 }
1754 Value *ShadowPtr = IRB.CreateExtractValue(ShadowOriginPtrs, 0);
1755 ShadowPtr = IRB.CreatePointerCast(ShadowPtr, MS.PtrTy);
1756 Value *OriginPtr = IRB.CreateExtractValue(ShadowOriginPtrs, 1);
1757
1758 return std::make_pair(ShadowPtr, OriginPtr);
1759 }
1760
1761 /// Addr can be a ptr or <N x ptr>. In both cases ShadowTy the shadow type of
1762 /// a single pointee.
1763 /// Returns <shadow_ptr, origin_ptr> or <<N x shadow_ptr>, <N x origin_ptr>>.
1764 std::pair<Value *, Value *> getShadowOriginPtrKernel(Value *Addr,
1765 IRBuilder<> &IRB,
1766 Type *ShadowTy,
1767 bool isStore) {
1768 VectorType *VectTy = dyn_cast<VectorType>(Addr->getType());
1769 if (!VectTy) {
1770 assert(Addr->getType()->isPointerTy());
1771 return getShadowOriginPtrKernelNoVec(Addr, IRB, ShadowTy, isStore);
1772 }
1773
1774 // TODO: Support callbacs with vectors of addresses.
1775 unsigned NumElements = cast<FixedVectorType>(VectTy)->getNumElements();
1776 Value *ShadowPtrs = ConstantInt::getNullValue(
1777 FixedVectorType::get(IRB.getPtrTy(), NumElements));
1778 Value *OriginPtrs = nullptr;
1779 if (MS.TrackOrigins)
1780 OriginPtrs = ConstantInt::getNullValue(
1781 FixedVectorType::get(IRB.getPtrTy(), NumElements));
1782 for (unsigned i = 0; i < NumElements; ++i) {
1783 Value *OneAddr =
1784 IRB.CreateExtractElement(Addr, ConstantInt::get(IRB.getInt32Ty(), i));
1785 auto [ShadowPtr, OriginPtr] =
1786 getShadowOriginPtrKernelNoVec(OneAddr, IRB, ShadowTy, isStore);
1787
1788 ShadowPtrs = IRB.CreateInsertElement(
1789 ShadowPtrs, ShadowPtr, ConstantInt::get(IRB.getInt32Ty(), i));
1790 if (MS.TrackOrigins)
1791 OriginPtrs = IRB.CreateInsertElement(
1792 OriginPtrs, OriginPtr, ConstantInt::get(IRB.getInt32Ty(), i));
1793 }
1794 return {ShadowPtrs, OriginPtrs};
1795 }
1796
1797 /// Returns true if the memory pointed to by \p Addr has no associated shadow
1798 /// memory. Pointers into such memory (e.g., x86 segment-relative pointers)
1799 /// cannot be mapped to shadow, nor be passed to the runtime library. Values
1800 /// loaded from such memory are treated as fully initialized, and values
1801 /// stored to it are checked eagerly.
1802 ///
1803 /// Conservatively, any non-default address space is treated as untracked.
1804 /// This includes address spaces that refer to ordinary memory (e.g., x86
1805 /// __ptr32/__ptr64), matching what ASan and TSan do.
1806 static bool isUntrackedAddrSpace(const Value *Addr) {
1807 return Addr->getType()->getScalarType()->getPointerAddressSpace() != 0;
1808 }
1809
1810 /// Mark the \p Size bytes of memory at \p Addr as initialized. In the
1811 /// kernel, this is done by calling \p KmsanUnpoisonFn(Addr, Size). If \p Ty
1812 /// is given, it is the type of the memory being unpoisoned.
1813 void unpoisonMemoryRange(IRBuilder<> &IRB, Value *Addr, Value *Size,
1814 FunctionCallee KmsanUnpoisonFn, Type *Ty = nullptr) {
1815 Size = IRB.CreateZExtOrTrunc(Size, MS.IntptrTy);
1816 if (MS.CompileKernel) {
1817 IRB.CreateCall(KmsanUnpoisonFn, {Addr, Size});
1818 return;
1819 }
1820 // The alignment of Addr is not known, so conservatively assume that the
1821 // shadow memory is unaligned.
1822 auto [ShadowPtr, _] =
1823 getShadowOriginPtrUserspace(Addr, IRB, IRB.getInt8Ty(), Align(1));
1824 // When Size is large, avoid StoreInst as it would expand to many
1825 // instructions.
1826 if (auto *CSize = dyn_cast<ConstantInt>(Size)) {
1827 uint64_t N = CSize->getZExtValue();
1828 if (N == 0)
1829 return;
1830 if (N <= 32) {
1831 Value *Clean = Ty ? getCleanShadow(Ty) : IRB.getIntN(N * 8, 0);
1832 IRB.CreateAlignedStore(Clean, ShadowPtr, Align(1));
1833 return;
1834 }
1835 }
1836 IRB.CreateMemSet(ShadowPtr, IRB.getInt8(0), Size, Align(1));
1837 }
1838
1839 std::pair<Value *, Value *> getShadowOriginPtr(Value *Addr, IRBuilder<> &IRB,
1840 Type *ShadowTy,
1841 MaybeAlign Alignment,
1842 bool isStore) {
1843 assert(!isUntrackedAddrSpace(Addr) &&
1844 "no shadow for memory in untracked address spaces");
1845 if (MS.CompileKernel)
1846 return getShadowOriginPtrKernel(Addr, IRB, ShadowTy, isStore);
1847 return getShadowOriginPtrUserspace(Addr, IRB, ShadowTy, Alignment);
1848 }
1849
1850 /// Compute the shadow address for a given function argument.
1851 ///
1852 /// Shadow = ParamTLS+ArgOffset.
1853 Value *getShadowPtrForArgument(IRBuilder<> &IRB, unsigned ArgOffset) {
1854 return IRB.CreatePtrAddWithUnsignedOffset(MS.ParamTLS, ArgOffset, "_msarg");
1855 }
1856
1857 /// Compute the origin address for a given function argument.
1858 Value *getOriginPtrForArgument(IRBuilder<> &IRB, unsigned ArgOffset) {
1859 if (!MS.TrackOrigins)
1860 return nullptr;
1861 return IRB.CreatePtrAddWithUnsignedOffset(MS.ParamOriginTLS, ArgOffset,
1862 "_msarg_o");
1863 }
1864
1865 /// Compute the shadow address for a retval.
1866 Value *getShadowPtrForRetval(IRBuilder<> &IRB) {
1867 return IRB.CreatePointerCast(MS.RetvalTLS, IRB.getPtrTy(0), "_msret");
1868 }
1869
1870 /// Compute the origin address for a retval.
1871 Value *getOriginPtrForRetval() {
1872 // We keep a single origin for the entire retval. Might be too optimistic.
1873 return MS.RetvalOriginTLS;
1874 }
1875
1876 /// Set SV to be the shadow value for V.
1877 void setShadow(Value *V, Value *SV) {
1878 assert(!ShadowMap.count(V) && "Values may only have one shadow");
1879
1880 // getShadowTy(VoidType) == nullptr
1881 if (SV && !V->getType()->isVoidTy() && getShadowTy(V) != SV->getType()) {
1882 LLVM_DEBUG(dbgs() << "V: " << *V << "\n");
1883 LLVM_DEBUG(dbgs() << "SV: " << *SV << "\n");
1884 assert(getShadowTy(V) == SV->getType() &&
1885 "setShadow called with mismatching types");
1886 }
1887
1888 ShadowMap[V] = PropagateShadow ? SV : getCleanShadow(V);
1889 }
1890
1891 /// Set Origin to be the origin value for V.
1892 void setOrigin(Value *V, Value *Origin) {
1893 if (!MS.TrackOrigins)
1894 return;
1895 assert(!OriginMap.count(V) && "Values may only have one origin");
1896 LLVM_DEBUG(dbgs() << "ORIGIN: " << *V << " ==> " << *Origin << "\n");
1897 OriginMap[V] = Origin;
1898 }
1899
1900 Constant *getCleanShadow(Type *OrigTy) {
1901 Type *ShadowTy = getShadowTy(OrigTy);
1902 if (!ShadowTy)
1903 return nullptr;
1904 return Constant::getNullValue(ShadowTy);
1905 }
1906
1907 /// Create a clean shadow value for a given value.
1908 ///
1909 /// Clean shadow (all zeroes) means all bits of the value are defined
1910 /// (initialized).
1911 Constant *getCleanShadow(Value *V) { return getCleanShadow(V->getType()); }
1912
1913 /// Create a dirty shadow of a given shadow type.
1914 Constant *getPoisonedShadow(Type *ShadowTy) {
1915 assert(ShadowTy);
1916 if (isa<IntegerType>(ShadowTy) || isa<VectorType>(ShadowTy))
1917 return Constant::getAllOnesValue(ShadowTy);
1918 if (ArrayType *AT = dyn_cast<ArrayType>(ShadowTy)) {
1919 SmallVector<Constant *, 4> Vals(AT->getNumElements(),
1920 getPoisonedShadow(AT->getElementType()));
1921 return ConstantArray::get(AT, Vals);
1922 }
1923 if (StructType *ST = dyn_cast<StructType>(ShadowTy)) {
1924 SmallVector<Constant *, 4> Vals;
1925 for (unsigned i = 0, n = ST->getNumElements(); i < n; i++)
1926 Vals.push_back(getPoisonedShadow(ST->getElementType(i)));
1927 return ConstantStruct::get(ST, Vals);
1928 }
1929 llvm_unreachable("Unexpected shadow type");
1930 }
1931
1932 /// Create a dirty shadow for a given value.
1933 Constant *getPoisonedShadow(Value *V) {
1934 Type *ShadowTy = getShadowTy(V);
1935 if (!ShadowTy)
1936 return nullptr;
1937 return getPoisonedShadow(ShadowTy);
1938 }
1939
1940 /// Create a clean (zero) origin.
1941 Value *getCleanOrigin() { return Constant::getNullValue(MS.OriginTy); }
1942
1943 /// Get the shadow value for a given Value.
1944 ///
1945 /// This function either returns the value set earlier with setShadow,
1946 /// or extracts if from ParamTLS (for function arguments).
1947 Value *getShadow(Value *V) {
1948 if (Instruction *I = dyn_cast<Instruction>(V)) {
1949 if (!PropagateShadow || I->getMetadata(LLVMContext::MD_nosanitize))
1950 return getCleanShadow(V);
1951 // For instructions the shadow is already stored in the map.
1952 Value *Shadow = ShadowMap[V];
1953 if (!Shadow) {
1954 LLVM_DEBUG(dbgs() << "No shadow: " << *V << "\n" << *(I->getParent()));
1955 assert(Shadow && "No shadow for a value");
1956 }
1957 return Shadow;
1958 }
1959 // Handle fully undefined values
1960 // (partially undefined constant vectors are handled later)
1961 if ([[maybe_unused]] UndefValue *U = dyn_cast<UndefValue>(V)) {
1962 Value *AllOnes = (PropagateShadow && PoisonUndef) ? getPoisonedShadow(V)
1963 : getCleanShadow(V);
1964 LLVM_DEBUG(dbgs() << "Undef: " << *U << " ==> " << *AllOnes << "\n");
1965 return AllOnes;
1966 }
1967 if (Argument *A = dyn_cast<Argument>(V)) {
1968 // For arguments we compute the shadow on demand and store it in the map.
1969 Value *&ShadowPtr = ShadowMap[V];
1970 if (ShadowPtr)
1971 return ShadowPtr;
1972 Function *F = A->getParent();
1973 IRBuilder<> EntryIRB(FnPrologueEnd);
1974 unsigned ArgOffset = 0;
1975 const DataLayout &DL = F->getDataLayout();
1976 for (auto &FArg : F->args()) {
1977 if (!FArg.getType()->isSized() || FArg.getType()->isScalableTy()) {
1978 LLVM_DEBUG(dbgs() << (FArg.getType()->isScalableTy()
1979 ? "vscale not fully supported\n"
1980 : "Arg is not sized\n"));
1981 if (A == &FArg) {
1982 ShadowPtr = getCleanShadow(V);
1983 setOrigin(A, getCleanOrigin());
1984 break;
1985 }
1986 continue;
1987 }
1988
1989 unsigned Size = FArg.hasByValAttr()
1990 ? DL.getTypeAllocSize(FArg.getParamByValType())
1991 : DL.getTypeAllocSize(FArg.getType());
1992
1993 if (A == &FArg) {
1994 bool Overflow = ArgOffset + Size > kParamTLSSize;
1995 if (FArg.hasByValAttr()) {
1996 // ByVal pointer itself has clean shadow. We copy the actual
1997 // argument shadow to the underlying memory.
1998 // Figure out maximal valid memcpy alignment.
1999 const Align ArgAlign = DL.getValueOrABITypeAlignment(
2000 FArg.getParamAlign(), FArg.getParamByValType());
2001 Value *CpShadowPtr, *CpOriginPtr;
2002 std::tie(CpShadowPtr, CpOriginPtr) =
2003 getShadowOriginPtr(V, EntryIRB, EntryIRB.getInt8Ty(), ArgAlign,
2004 /*isStore*/ true);
2005 if (!PropagateShadow || Overflow) {
2006 // ParamTLS overflow.
2007 EntryIRB.CreateMemSet(
2008 CpShadowPtr, Constant::getNullValue(EntryIRB.getInt8Ty()),
2009 Size, ArgAlign);
2010 } else {
2011 Value *Base = getShadowPtrForArgument(EntryIRB, ArgOffset);
2012 const Align CopyAlign = std::min(ArgAlign, kShadowTLSAlignment);
2013 [[maybe_unused]] Value *Cpy = EntryIRB.CreateMemCpy(
2014 CpShadowPtr, CopyAlign, Base, CopyAlign, Size);
2015 LLVM_DEBUG(dbgs() << " ByValCpy: " << *Cpy << "\n");
2016
2017 if (MS.TrackOrigins) {
2018 Value *OriginPtr = getOriginPtrForArgument(EntryIRB, ArgOffset);
2019 // FIXME: OriginSize should be:
2020 // alignTo(V % kMinOriginAlignment + Size, kMinOriginAlignment)
2021 unsigned OriginSize = alignTo(Size, kMinOriginAlignment);
2022 EntryIRB.CreateMemCpy(
2023 CpOriginPtr,
2024 /* by getShadowOriginPtr */ kMinOriginAlignment, OriginPtr,
2025 /* by origin_tls[ArgOffset] */ kMinOriginAlignment,
2026 OriginSize);
2027 }
2028 }
2029 }
2030
2031 if (!PropagateShadow || Overflow || FArg.hasByValAttr() ||
2032 (MS.EagerChecks && FArg.hasAttribute(Attribute::NoUndef))) {
2033 ShadowPtr = getCleanShadow(V);
2034 setOrigin(A, getCleanOrigin());
2035 } else {
2036 // Shadow over TLS
2037 Value *Base = getShadowPtrForArgument(EntryIRB, ArgOffset);
2038 ShadowPtr = EntryIRB.CreateAlignedLoad(getShadowTy(&FArg), Base,
2040 if (MS.TrackOrigins) {
2041 Value *OriginPtr = getOriginPtrForArgument(EntryIRB, ArgOffset);
2042 setOrigin(A, EntryIRB.CreateLoad(MS.OriginTy, OriginPtr));
2043 }
2044 }
2046 << " ARG: " << FArg << " ==> " << *ShadowPtr << "\n");
2047 break;
2048 }
2049
2050 ArgOffset += alignTo(Size, kShadowTLSAlignment);
2051 }
2052 assert(ShadowPtr && "Could not find shadow for an argument");
2053 return ShadowPtr;
2054 }
2055
2056 // Check for partially-undefined constant vectors
2057 // TODO: scalable vectors (this is hard because we do not have IRBuilder)
2058 if (isa<FixedVectorType>(V->getType()) && isa<Constant>(V) &&
2059 cast<Constant>(V)->containsUndefOrPoisonElement() && PropagateShadow &&
2060 PoisonUndefVectors) {
2061 unsigned NumElems = cast<FixedVectorType>(V->getType())->getNumElements();
2062 SmallVector<Constant *, 32> ShadowVector(NumElems);
2063 for (unsigned i = 0; i != NumElems; ++i) {
2064 Constant *Elem = cast<Constant>(V)->getAggregateElement(i);
2065 ShadowVector[i] = isa<UndefValue>(Elem) ? getPoisonedShadow(Elem)
2066 : getCleanShadow(Elem);
2067 }
2068
2069 Value *ShadowConstant = ConstantVector::get(ShadowVector);
2070 LLVM_DEBUG(dbgs() << "Partial undef constant vector: " << *V << " ==> "
2071 << *ShadowConstant << "\n");
2072
2073 return ShadowConstant;
2074 }
2075
2076 // TODO: partially-undefined constant arrays, structures, and nested types
2077
2078 // For everything else the shadow is zero.
2079 return getCleanShadow(V);
2080 }
2081
2082 /// Get the shadow for i-th argument of the instruction I.
2083 Value *getShadow(Instruction *I, int i) {
2084 return getShadow(I->getOperand(i));
2085 }
2086
2087 /// Get the origin for a value.
2088 Value *getOrigin(Value *V) {
2089 if (!MS.TrackOrigins)
2090 return nullptr;
2091 if (!PropagateShadow || isa<Constant>(V) || isa<InlineAsm>(V))
2092 return getCleanOrigin();
2094 "Unexpected value type in getOrigin()");
2095 if (Instruction *I = dyn_cast<Instruction>(V)) {
2096 if (I->getMetadata(LLVMContext::MD_nosanitize))
2097 return getCleanOrigin();
2098 }
2099 Value *Origin = OriginMap[V];
2100 assert(Origin && "Missing origin");
2101 return Origin;
2102 }
2103
2104 /// Get the origin for i-th argument of the instruction I.
2105 Value *getOrigin(Instruction *I, int i) {
2106 return getOrigin(I->getOperand(i));
2107 }
2108
2109 /// Remember the place where a shadow check should be inserted.
2110 ///
2111 /// This location will be later instrumented with a check that will print a
2112 /// UMR warning in runtime if the shadow value is not 0.
2113 void insertCheckShadow(Value *Shadow, Value *Origin, Instruction *OrigIns) {
2114 assert(Shadow);
2115 if (!InsertChecks)
2116 return;
2117
2118 if (!DebugCounter::shouldExecute(DebugInsertCheck)) {
2119 LLVM_DEBUG(dbgs() << "Skipping check of " << *Shadow << " before "
2120 << *OrigIns << "\n");
2121 return;
2122 }
2123
2124 Type *ShadowTy = Shadow->getType();
2125 if (isScalableNonVectorType(ShadowTy)) {
2126 LLVM_DEBUG(dbgs() << "Skipping check of scalable non-vector " << *Shadow
2127 << " before " << *OrigIns << "\n");
2128 return;
2129 }
2130#ifndef NDEBUG
2131 assert((isa<IntegerType>(ShadowTy) || isa<VectorType>(ShadowTy) ||
2132 isa<StructType>(ShadowTy) || isa<ArrayType>(ShadowTy)) &&
2133 "Can only insert checks for integer, vector, and aggregate shadow "
2134 "types");
2135#endif
2136 InstrumentationList.push_back(
2137 ShadowOriginAndInsertPoint(Shadow, Origin, OrigIns));
2138 }
2139
2140 /// Get shadow for value, and remember the place where a shadow check should
2141 /// be inserted.
2142 ///
2143 /// This location will be later instrumented with a check that will print a
2144 /// UMR warning in runtime if the value is not fully defined.
2145 void insertCheckShadowOf(Value *Val, Instruction *OrigIns) {
2146 assert(Val);
2147 Value *Shadow, *Origin;
2148 if (Opts.msan_check_constant_shadow) {
2149 Shadow = getShadow(Val);
2150 if (!Shadow)
2151 return;
2152 Origin = getOrigin(Val);
2153 } else {
2154 Shadow = dyn_cast_or_null<Instruction>(getShadow(Val));
2155 if (!Shadow)
2156 return;
2157 Origin = dyn_cast_or_null<Instruction>(getOrigin(Val));
2158 }
2159 insertCheckShadow(Shadow, Origin, OrigIns);
2160 }
2161
2163 switch (a) {
2164 case AtomicOrdering::NotAtomic:
2165 return AtomicOrdering::NotAtomic;
2166 case AtomicOrdering::Unordered:
2167 case AtomicOrdering::Monotonic:
2168 case AtomicOrdering::Release:
2169 return AtomicOrdering::Release;
2170 case AtomicOrdering::Acquire:
2171 case AtomicOrdering::AcquireRelease:
2172 return AtomicOrdering::AcquireRelease;
2173 case AtomicOrdering::SequentiallyConsistent:
2174 return AtomicOrdering::SequentiallyConsistent;
2175 }
2176 llvm_unreachable("Unknown ordering");
2177 }
2178
2179 Value *makeAddReleaseOrderingTable(IRBuilder<> &IRB) {
2180 constexpr int NumOrderings = (int)AtomicOrderingCABI::seq_cst + 1;
2181 uint32_t OrderingTable[NumOrderings] = {};
2182
2183 OrderingTable[(int)AtomicOrderingCABI::relaxed] =
2184 OrderingTable[(int)AtomicOrderingCABI::release] =
2185 (int)AtomicOrderingCABI::release;
2186 OrderingTable[(int)AtomicOrderingCABI::consume] =
2187 OrderingTable[(int)AtomicOrderingCABI::acquire] =
2188 OrderingTable[(int)AtomicOrderingCABI::acq_rel] =
2189 (int)AtomicOrderingCABI::acq_rel;
2190 OrderingTable[(int)AtomicOrderingCABI::seq_cst] =
2191 (int)AtomicOrderingCABI::seq_cst;
2192
2193 return ConstantDataVector::get(IRB.getContext(), OrderingTable);
2194 }
2195
2197 switch (a) {
2198 case AtomicOrdering::NotAtomic:
2199 return AtomicOrdering::NotAtomic;
2200 case AtomicOrdering::Unordered:
2201 case AtomicOrdering::Monotonic:
2202 case AtomicOrdering::Acquire:
2203 return AtomicOrdering::Acquire;
2204 case AtomicOrdering::Release:
2205 case AtomicOrdering::AcquireRelease:
2206 return AtomicOrdering::AcquireRelease;
2207 case AtomicOrdering::SequentiallyConsistent:
2208 return AtomicOrdering::SequentiallyConsistent;
2209 }
2210 llvm_unreachable("Unknown ordering");
2211 }
2212
2213 Value *makeAddAcquireOrderingTable(IRBuilder<> &IRB) {
2214 constexpr int NumOrderings = (int)AtomicOrderingCABI::seq_cst + 1;
2215 uint32_t OrderingTable[NumOrderings] = {};
2216
2217 OrderingTable[(int)AtomicOrderingCABI::relaxed] =
2218 OrderingTable[(int)AtomicOrderingCABI::acquire] =
2219 OrderingTable[(int)AtomicOrderingCABI::consume] =
2220 (int)AtomicOrderingCABI::acquire;
2221 OrderingTable[(int)AtomicOrderingCABI::release] =
2222 OrderingTable[(int)AtomicOrderingCABI::acq_rel] =
2223 (int)AtomicOrderingCABI::acq_rel;
2224 OrderingTable[(int)AtomicOrderingCABI::seq_cst] =
2225 (int)AtomicOrderingCABI::seq_cst;
2226
2227 return ConstantDataVector::get(IRB.getContext(), OrderingTable);
2228 }
2229
2230 // ------------------- Visitors.
2231 using InstVisitor<MemorySanitizerVisitor>::visit;
2232 void visit(Instruction &I) {
2233 if (I.getMetadata(LLVMContext::MD_nosanitize))
2234 return;
2235 // Don't want to visit if we're in the prologue
2236 if (isInPrologue(I))
2237 return;
2238 if (!DebugCounter::shouldExecute(DebugInstrumentInstruction)) {
2239 LLVM_DEBUG(dbgs() << "Skipping instruction: " << I << "\n");
2240 // We still need to set the shadow and origin to clean values.
2241 setShadow(&I, getCleanShadow(&I));
2242 setOrigin(&I, getCleanOrigin());
2243 return;
2244 }
2245
2246 Instructions.push_back(&I);
2247 }
2248
2249 /// Instrument LoadInst
2250 ///
2251 /// Loads the corresponding shadow and (optionally) origin.
2252 /// Optionally, checks that the load address is fully defined.
2253 void visitLoadInst(LoadInst &I) {
2254 assert(I.getType()->isSized() && "Load type must have size");
2255 assert(!I.getMetadata(LLVMContext::MD_nosanitize));
2256 NextNodeIRBuilder IRB(&I);
2257 Type *ShadowTy = getShadowTy(&I);
2258 Value *Addr = I.getPointerOperand();
2259 Value *ShadowPtr = nullptr, *OriginPtr = nullptr;
2260 const Align Alignment = I.getAlign();
2261 const bool LoadShadow = PropagateShadow && !isUntrackedAddrSpace(Addr);
2262 if (LoadShadow) {
2263 std::tie(ShadowPtr, OriginPtr) =
2264 getShadowOriginPtr(Addr, IRB, ShadowTy, Alignment, /*isStore*/ false);
2265 setShadow(&I,
2266 IRB.CreateAlignedLoad(ShadowTy, ShadowPtr, Alignment, "_msld"));
2267 } else {
2268 setShadow(&I, getCleanShadow(&I));
2269 }
2270
2271 if (Opts.msan_check_access_address)
2272 insertCheckShadowOf(I.getPointerOperand(), &I);
2273
2274 if (I.isAtomic())
2275 I.setOrdering(addAcquireOrdering(I.getOrdering()));
2276
2277 if (MS.TrackOrigins) {
2278 if (LoadShadow) {
2279 const Align OriginAlignment = std::max(kMinOriginAlignment, Alignment);
2280 setOrigin(
2281 &I, IRB.CreateAlignedLoad(MS.OriginTy, OriginPtr, OriginAlignment));
2282 } else {
2283 setOrigin(&I, getCleanOrigin());
2284 }
2285 }
2286 }
2287
2288 /// Instrument StoreInst
2289 ///
2290 /// Stores the corresponding shadow and (optionally) origin.
2291 /// Optionally, checks that the store address is fully defined.
2292 void visitStoreInst(StoreInst &I) {
2293 StoreList.push_back(&I);
2294 if (Opts.msan_check_access_address)
2295 insertCheckShadowOf(I.getPointerOperand(), &I);
2296 // There is no shadow to store for memory in untracked address spaces, so
2297 // the value would come back as initialized when loaded again. Check the
2298 // stored value eagerly instead, as is done for inline asm inputs.
2299 if (isUntrackedAddrSpace(I.getPointerOperand()))
2300 insertCheckShadowOf(I.getValueOperand(), &I);
2301 }
2302
2303 void handleCASOrRMW(Instruction &I) {
2305
2306 IRBuilder<> IRB(&I);
2307 Value *Addr = I.getOperand(0);
2308 Value *Val = I.getOperand(1);
2309 Value *ShadowPtr = nullptr;
2310 if (!isUntrackedAddrSpace(Addr))
2311 ShadowPtr = getShadowOriginPtr(Addr, IRB, getShadowTy(Val), Align(1),
2312 /*isStore*/ true)
2313 .first;
2314
2315 if (Opts.msan_check_access_address)
2316 insertCheckShadowOf(Addr, &I);
2317
2318 // Only test the conditional argument of cmpxchg instruction.
2319 // The other argument can potentially be uninitialized, but we can not
2320 // detect this situation reliably without possible false positives.
2322 insertCheckShadowOf(Val, &I);
2323
2324 if (ShadowPtr)
2325 IRB.CreateStore(getCleanShadow(Val), ShadowPtr);
2326
2327 setShadow(&I, getCleanShadow(&I));
2328 setOrigin(&I, getCleanOrigin());
2329 }
2330
2331 void visitAtomicRMWInst(AtomicRMWInst &I) {
2332 handleCASOrRMW(I);
2333 I.setOrdering(addReleaseOrdering(I.getOrdering()));
2334 }
2335
2336 void visitAtomicCmpXchgInst(AtomicCmpXchgInst &I) {
2337 handleCASOrRMW(I);
2338 I.setSuccessOrdering(addReleaseOrdering(I.getSuccessOrdering()));
2339 }
2340
2341 /// Generic handler to compute shadow for == and != comparisons.
2342 ///
2343 /// This function is used by handleEqualityComparison and visitSwitchInst.
2344 ///
2345 /// Sometimes the comparison result is known even if some of the bits of the
2346 /// arguments are not.
2347 Value *propagateEqualityComparison(IRBuilder<> &IRB, Value *A, Value *B,
2348 Value *Sa, Value *Sb) {
2349 assert(getShadowTy(A) == Sa->getType());
2350 assert(getShadowTy(B) == Sb->getType());
2351
2352 // Get rid of pointers and vectors of pointers.
2353 // For ints (and vectors of ints), types of A and Sa match,
2354 // and this is a no-op.
2355 A = IRB.CreatePointerCast(A, Sa->getType());
2356 B = IRB.CreatePointerCast(B, Sb->getType());
2357
2358 // A == B <==> (C = A^B) == 0
2359 // A != B <==> (C = A^B) != 0
2360 // Sc = Sa | Sb
2361 Value *C = IRB.CreateXor(A, B);
2362 Value *Sc = IRB.CreateOr(Sa, Sb);
2363 // Now dealing with i = (C == 0) comparison (or C != 0, does not matter now)
2364 // Result is defined if one of the following is true
2365 // * there is a defined 1 bit in C
2366 // * C is fully defined
2367 // Si = !(C & ~Sc) && Sc
2369 Value *MinusOne = Constant::getAllOnesValue(Sc->getType());
2370 Value *LHS = IRB.CreateICmpNE(Sc, Zero);
2371 Value *RHS =
2372 IRB.CreateICmpEQ(IRB.CreateAnd(IRB.CreateXor(Sc, MinusOne), C), Zero);
2373 Value *Si = IRB.CreateAnd(LHS, RHS);
2374 Si->setName("_msprop_icmp");
2375
2376 return Si;
2377 }
2378
2379 // Instrument:
2380 // switch i32 %Val, label %else [ i32 0, label %A
2381 // i32 1, label %B
2382 // i32 2, label %C ]
2383 //
2384 // Typically, the switch input value (%Val) is fully initialized.
2385 //
2386 // Sometimes the compiler may convert (icmp + br) into a switch statement.
2387 // MSan allows icmp eq/ne with partly initialized inputs to still result in a
2388 // fully initialized output, if there exists a bit that is initialized in
2389 // both inputs with a differing value. For compatibility, we support this in
2390 // the switch instrumentation as well. Note that this edge case only applies
2391 // if the switch input value does not match *any* of the cases (matching any
2392 // of the cases requires an exact, fully initialized match).
2393 //
2394 // ShadowCases = 0
2395 // | propagateEqualityComparison(Val, 0)
2396 // | propagateEqualityComparison(Val, 1)
2397 // | propagateEqualityComparison(Val, 2))
2398 void visitSwitchInst(SwitchInst &SI) {
2399 IRBuilder<> IRB(&SI);
2400
2401 Value *Val = SI.getCondition();
2402 Value *ShadowVal = getShadow(Val);
2403 // TODO: add fast path - if the condition is fully initialized, we know
2404 // there is no UUM, without needing to consider the case values below.
2405
2406 // Some code (e.g., AMDGPUGenMCCodeEmitter.inc) has tens of thousands of
2407 // cases. This results in an extremely long chained expression for MSan's
2408 // switch instrumentation, which can cause the JumpThreadingPass to have a
2409 // stack overflow or excessive runtime. We limit the number of cases
2410 // considered, with the tradeoff of niche false negatives.
2411 // TODO: figure out a better solution.
2412 int casesToConsider = Opts.msan_switch_precision;
2413
2414 Value *ShadowCases = nullptr;
2415 for (auto Case : SI.cases()) {
2416 if (casesToConsider <= 0)
2417 break;
2418
2419 Value *Comparator = Case.getCaseValue();
2420 // TODO: some simplification is possible when comparing multiple cases
2421 // simultaneously.
2422 Value *ComparisonShadow = propagateEqualityComparison(
2423 IRB, Val, Comparator, ShadowVal, getShadow(Comparator));
2424
2425 if (ShadowCases)
2426 ShadowCases = IRB.CreateOr(ShadowCases, ComparisonShadow);
2427 else
2428 ShadowCases = ComparisonShadow;
2429
2430 casesToConsider--;
2431 }
2432
2433 if (ShadowCases)
2434 insertCheckShadow(ShadowCases, getOrigin(Val), &SI);
2435 }
2436
2437 // Vector manipulation.
2438 void visitExtractElementInst(ExtractElementInst &I) {
2439 insertCheckShadowOf(I.getOperand(1), &I);
2440 IRBuilder<> IRB(&I);
2441 setShadow(&I, IRB.CreateExtractElement(getShadow(&I, 0), I.getOperand(1),
2442 "_msprop"));
2443 setOrigin(&I, getOrigin(&I, 0));
2444 }
2445
2446 void visitInsertElementInst(InsertElementInst &I) {
2447 insertCheckShadowOf(I.getOperand(2), &I);
2448 IRBuilder<> IRB(&I);
2449 auto *Shadow0 = getShadow(&I, 0);
2450 auto *Shadow1 = getShadow(&I, 1);
2451 setShadow(&I, IRB.CreateInsertElement(Shadow0, Shadow1, I.getOperand(2),
2452 "_msprop"));
2453 setOriginForNaryOp(I);
2454 }
2455
2456 void visitShuffleVectorInst(ShuffleVectorInst &I) {
2457 IRBuilder<> IRB(&I);
2458 auto *Shadow0 = getShadow(&I, 0);
2459 auto *Shadow1 = getShadow(&I, 1);
2460 setShadow(&I, IRB.CreateShuffleVector(Shadow0, Shadow1, I.getShuffleMask(),
2461 "_msprop"));
2462 setOriginForNaryOp(I);
2463 }
2464
2465 // Casts.
2466 void visitSExtInst(SExtInst &I) {
2467 IRBuilder<> IRB(&I);
2468 setShadow(&I, IRB.CreateSExt(getShadow(&I, 0), I.getType(), "_msprop"));
2469 setOrigin(&I, getOrigin(&I, 0));
2470 }
2471
2472 void visitZExtInst(ZExtInst &I) {
2473 IRBuilder<> IRB(&I);
2474 setShadow(&I, IRB.CreateZExt(getShadow(&I, 0), I.getType(), "_msprop"));
2475 setOrigin(&I, getOrigin(&I, 0));
2476 }
2477
2478 void visitTruncInst(TruncInst &I) {
2479 IRBuilder<> IRB(&I);
2480 setShadow(&I, IRB.CreateTrunc(getShadow(&I, 0), I.getType(), "_msprop"));
2481 setOrigin(&I, getOrigin(&I, 0));
2482 }
2483
2484 void visitBitCastInst(BitCastInst &I) {
2485 // Special case: if this is the bitcast (there is exactly 1 allowed) between
2486 // a musttail call and a ret, don't instrument. New instructions are not
2487 // allowed after a musttail call.
2488 if (auto *CI = dyn_cast<CallInst>(I.getOperand(0)))
2489 if (CI->isMustTailCall())
2490 return;
2491 IRBuilder<> IRB(&I);
2492 setShadow(&I, IRB.CreateBitCast(getShadow(&I, 0), getShadowTy(&I)));
2493 setOrigin(&I, getOrigin(&I, 0));
2494 }
2495
2496 void visitAddrSpaceCastInst(AddrSpaceCastInst &I) {
2497 IRBuilder<> IRB(&I);
2498 setShadow(&I, IRB.CreateIntCast(getShadow(&I, 0), getShadowTy(&I), false,
2499 "_msprop_addrspacecast"));
2500 setOrigin(&I, getOrigin(&I, 0));
2501 }
2502
2503 void visitPtrToIntInst(PtrToIntInst &I) {
2504 IRBuilder<> IRB(&I);
2505 setShadow(&I, IRB.CreateIntCast(getShadow(&I, 0), getShadowTy(&I), false,
2506 "_msprop_ptrtoint"));
2507 setOrigin(&I, getOrigin(&I, 0));
2508 }
2509
2510 void visitPtrToAddrInst(PtrToAddrInst &I) {
2511 IRBuilder<> IRB(&I);
2512 setShadow(&I, IRB.CreateIntCast(getShadow(&I, 0), getShadowTy(&I), false,
2513 "_msprop_ptrtoaddr"));
2514 setOrigin(&I, getOrigin(&I, 0));
2515 }
2516
2517 void visitIntToPtrInst(IntToPtrInst &I) {
2518 IRBuilder<> IRB(&I);
2519 setShadow(&I, IRB.CreateIntCast(getShadow(&I, 0), getShadowTy(&I), false,
2520 "_msprop_inttoptr"));
2521 setOrigin(&I, getOrigin(&I, 0));
2522 }
2523
2524 /// Handle LLVM and NEON vector convert intrinsics.
2525 ///
2526 /// e.g., <4 x i32> @llvm.aarch64.neon.fcvtpu.v4i32.v4f32(<4 x float>)
2527 /// i32 @llvm.aarch64.neon.fcvtms.i32.f64 (double)
2528 /// <2 x i32> @fptoui (<2 x float>)
2529 /// i64 @llvm.fptosi.sat.i64.f64(double)
2530 ///
2531 /// Note that the size of input/output elements can differ e.g.,
2532 /// double @sitofp(i32)
2533 /// but the number of elements must be the same.
2534 ///
2535 /// For conversions to or from fixed-point, there is a trailing argument to
2536 /// indicate the fixed-point precision:
2537 /// - <4 x float> llvm.aarch64.neon.vcvtfxs2fp.v4f32.v4i32(<4 x i32>, i32)
2538 /// - <4 x i32> llvm.aarch64.neon.vcvtfp2fxu.v4i32.v4f32(<4 x float>, i32)
2539 ///
2540 /// For x86 SSE vector convert intrinsics, see
2541 /// handleSSEVectorConvertIntrinsic().
2542 void handleGenericVectorConvertIntrinsic(Instruction &I, bool FixedPoint) {
2543 [[maybe_unused]] unsigned NumArgs = I.getNumOperands();
2544 if (auto *CI = dyn_cast<CallInst>(&I))
2545 NumArgs = CI->arg_size();
2546
2547 if (FixedPoint) {
2548 assert(NumArgs == 2);
2549 Value *Precision = I.getOperand(1);
2550 insertCheckShadowOf(Precision, &I);
2551 } else {
2552 assert(NumArgs == 1);
2553 }
2554
2555 IRBuilder<> IRB(&I);
2556 Value *S0 = getShadow(&I, 0);
2557
2558 /// For scalars:
2559 /// Since they are converting from floating-point to integer, or between
2560 /// different width floating-point values, the output is:
2561 /// - fully uninitialized if *any* bit of the input is uninitialized
2562 /// - fully ininitialized if all bits of the input are ininitialized
2563 /// We apply the same principle on a per-field basis for vectors.
2564 Value *OutShadow = IRB.CreateSExt(IRB.CreateICmpNE(S0, getCleanShadow(S0)),
2565 getShadowTy(&I));
2566 setShadow(&I, OutShadow);
2567 setOriginForNaryOp(I);
2568 }
2569
2570 void visitFPToSIInst(CastInst &I) {
2571 handleGenericVectorConvertIntrinsic(I, /*FixedPoint=*/false);
2572 }
2573 void visitFPToUIInst(CastInst &I) {
2574 handleGenericVectorConvertIntrinsic(I, /*FixedPoint=*/false);
2575 }
2576 void visitSIToFPInst(CastInst &I) {
2577 handleGenericVectorConvertIntrinsic(I, /*FixedPoint=*/false);
2578 }
2579 void visitUIToFPInst(CastInst &I) {
2580 handleGenericVectorConvertIntrinsic(I, /*FixedPoint=*/false);
2581 }
2582
2583 void visitFPExtInst(CastInst &I) {
2584 handleGenericVectorConvertIntrinsic(I, /*FixedPoint=*/false);
2585 }
2586 void visitFPTruncInst(CastInst &I) {
2587 handleGenericVectorConvertIntrinsic(I, /*FixedPoint=*/false);
2588 }
2589
2590 /// Generic handler to compute shadow for bitwise AND.
2591 ///
2592 /// This is used by 'visitAnd' but also as a primitive for other handlers.
2593 ///
2594 /// This code is precise: it implements the rule that "And" of an initialized
2595 /// zero bit always results in an initialized value:
2596 // 1&1 => 1; 0&1 => 0; p&1 => p;
2597 // 1&0 => 0; 0&0 => 0; p&0 => 0;
2598 // 1&p => p; 0&p => 0; p&p => p;
2599 //
2600 // S = (S1 & S2) | (V1 & S2) | (S1 & V2)
2601 Value *handleBitwiseAnd(IRBuilder<> &IRB, Value *V1, Value *V2, Value *S1,
2602 Value *S2) {
2603 // "The two arguments to the ‘and’ instruction must be integer or vector
2604 // of integer values. Both arguments must have identical types."
2605 //
2606 // We enforce this condition for all callers to handleBitwiseAnd(); callers
2607 // with non-integer types should call CreateAppToShadowCast() themselves.
2608 assert(V1->getType()->isIntOrIntVectorTy());
2609 assert(V1->getType() == V2->getType());
2610
2611 // Conveniently, getShadowTy() of Int/IntVector returns the original type.
2612 assert(V1->getType() == S1->getType());
2613 assert(V2->getType() == S2->getType());
2614
2615 Value *S1S2 = IRB.CreateAnd(S1, S2);
2616 Value *V1S2 = IRB.CreateAnd(V1, S2);
2617 Value *S1V2 = IRB.CreateAnd(S1, V2);
2618
2619 return IRB.CreateOr({S1S2, V1S2, S1V2});
2620 }
2621
2622 /// Handler for bitwise AND operator.
2623 void visitAnd(BinaryOperator &I) {
2624 IRBuilder<> IRB(&I);
2625 Value *V1 = I.getOperand(0);
2626 Value *V2 = I.getOperand(1);
2627 Value *S1 = getShadow(&I, 0);
2628 Value *S2 = getShadow(&I, 1);
2629
2630 Value *OutShadow = handleBitwiseAnd(IRB, V1, V2, S1, S2);
2631
2632 setShadow(&I, OutShadow);
2633 setOriginForNaryOp(I);
2634 }
2635
2636 void visitOr(BinaryOperator &I) {
2637 IRBuilder<> IRB(&I);
2638 // "Or" of 1 and a poisoned value results in unpoisoned value:
2639 // 1|1 => 1; 0|1 => 1; p|1 => 1;
2640 // 1|0 => 1; 0|0 => 0; p|0 => p;
2641 // 1|p => 1; 0|p => p; p|p => p;
2642 //
2643 // S = (S1 & S2) | (~V1 & S2) | (S1 & ~V2)
2644 //
2645 // If the "disjoint OR" property is violated, the result is poison, and
2646 // hence the entire shadow is uninitialized:
2647 // S = S | SignExt(V1 & V2 != 0)
2648 Value *S1 = getShadow(&I, 0);
2649 Value *S2 = getShadow(&I, 1);
2650 Value *V1 = I.getOperand(0);
2651 Value *V2 = I.getOperand(1);
2652
2653 // "The two arguments to the ‘or’ instruction must be integer or vector
2654 // of integer values. Both arguments must have identical types."
2655 assert(V1->getType()->isIntOrIntVectorTy());
2656 assert(V1->getType() == V2->getType());
2657
2658 // Conveniently, getShadowTy() of Int/IntVector returns the original type.
2659 assert(V1->getType() == S1->getType());
2660 assert(V2->getType() == S2->getType());
2661
2662 Value *NotV1 = IRB.CreateNot(V1);
2663 Value *NotV2 = IRB.CreateNot(V2);
2664
2665 Value *S1S2 = IRB.CreateAnd(S1, S2);
2666 Value *S2NotV1 = IRB.CreateAnd(NotV1, S2);
2667 Value *S1NotV2 = IRB.CreateAnd(S1, NotV2);
2668
2669 Value *S = IRB.CreateOr({S1S2, S2NotV1, S1NotV2});
2670
2671 if (Opts.msan_precise_disjoint_or &&
2672 cast<PossiblyDisjointInst>(&I)->isDisjoint()) {
2673 Value *V1V2 = IRB.CreateAnd(V1, V2);
2674 Value *DisjointOrShadow = IRB.CreateSExt(
2675 IRB.CreateICmpNE(V1V2, getCleanShadow(V1V2)), V1V2->getType());
2676 S = IRB.CreateOr(S, DisjointOrShadow, "_ms_disjoint");
2677 }
2678
2679 setShadow(&I, S);
2680 setOriginForNaryOp(I);
2681 }
2682
2683 /// Default propagation of shadow and/or origin.
2684 ///
2685 /// This class implements the general case of shadow propagation, used in all
2686 /// cases where we don't know and/or don't care about what the operation
2687 /// actually does. It converts all input shadow values to a common type
2688 /// (extending or truncating as necessary), and bitwise OR's them.
2689 ///
2690 /// This is much cheaper than inserting checks (i.e. requiring inputs to be
2691 /// fully initialized), and less prone to false positives.
2692 ///
2693 /// This class also implements the general case of origin propagation. For a
2694 /// Nary operation, result origin is set to the origin of an argument that is
2695 /// not entirely initialized. If there is more than one such arguments, the
2696 /// rightmost of them is picked. It does not matter which one is picked if all
2697 /// arguments are initialized.
2698 template <bool CombineShadow> class Combiner {
2699 Value *Shadow = nullptr;
2700 Value *Origin = nullptr;
2701 IRBuilder<> &IRB;
2702 MemorySanitizerVisitor *MSV;
2703
2704 public:
2705 Combiner(MemorySanitizerVisitor *MSV, IRBuilder<> &IRB)
2706 : IRB(IRB), MSV(MSV) {}
2707
2708 /// Add a pair of shadow and origin values to the mix.
2709 Combiner &Add(Value *OpShadow, Value *OpOrigin) {
2710 if (CombineShadow) {
2711 assert(OpShadow);
2712 if (!Shadow)
2713 Shadow = OpShadow;
2714 else {
2715 OpShadow = MSV->CreateShadowCast(IRB, OpShadow, Shadow->getType());
2716 Shadow = IRB.CreateOr(Shadow, OpShadow, "_msprop");
2717 }
2718 }
2719
2720 if (MSV->MS.TrackOrigins) {
2721 assert(OpOrigin);
2722 if (!Origin) {
2723 Origin = OpOrigin;
2724 } else {
2725 Constant *ConstOrigin = dyn_cast<Constant>(OpOrigin);
2726 // No point in adding something that might result in 0 origin value.
2727 if (!ConstOrigin || !ConstOrigin->isNullValue()) {
2728 Value *Cond = MSV->convertToBool(OpShadow, IRB);
2729 Origin = IRB.CreateSelect(Cond, OpOrigin, Origin);
2730 }
2731 }
2732 }
2733 return *this;
2734 }
2735
2736 /// Add an application value to the mix.
2737 Combiner &Add(Value *V) {
2738 Value *OpShadow = MSV->getShadow(V);
2739 Value *OpOrigin = MSV->MS.TrackOrigins ? MSV->getOrigin(V) : nullptr;
2740 return Add(OpShadow, OpOrigin);
2741 }
2742
2743 /// Set the current combined values as the given instruction's shadow
2744 /// and origin.
2745 void Done(Instruction *I) {
2746 if (CombineShadow) {
2747 assert(Shadow);
2748 Shadow = MSV->CreateShadowCast(IRB, Shadow, MSV->getShadowTy(I));
2749 MSV->setShadow(I, Shadow);
2750 }
2751 if (MSV->MS.TrackOrigins) {
2752 assert(Origin);
2753 MSV->setOrigin(I, Origin);
2754 }
2755 }
2756
2757 /// Store the current combined value at the specified origin
2758 /// location.
2759 void DoneAndStoreOrigin(TypeSize TS, Value *OriginPtr) {
2760 if (MSV->MS.TrackOrigins) {
2761 assert(Origin);
2762 MSV->paintOrigin(IRB, Origin, OriginPtr, TS, kMinOriginAlignment);
2763 }
2764 }
2765 };
2766
2767 using ShadowAndOriginCombiner = Combiner<true>;
2768 using OriginCombiner = Combiner<false>;
2769
2770 /// Propagate origin for arbitrary operation.
2771 void setOriginForNaryOp(Instruction &I) {
2772 if (!MS.TrackOrigins)
2773 return;
2774 IRBuilder<> IRB(&I);
2775 OriginCombiner OC(this, IRB);
2776 for (Use &Op : I.operands())
2777 OC.Add(Op.get());
2778 OC.Done(&I);
2779 }
2780
2781 size_t VectorOrPrimitiveTypeSizeInBits(Type *Ty) {
2782 assert(!(Ty->isVectorTy() && Ty->getScalarType()->isPointerTy()) &&
2783 "Vector of pointers is not a valid shadow type");
2784 return Ty->isVectorTy() ? cast<FixedVectorType>(Ty)->getNumElements() *
2786 : Ty->getPrimitiveSizeInBits();
2787 }
2788
2789 /// Cast between two shadow types, extending or truncating as
2790 /// necessary.
2791 Value *CreateShadowCast(IRBuilder<> &IRB, Value *V, Type *dstTy,
2792 bool Signed = false) {
2793 Type *srcTy = V->getType();
2794 if (srcTy == dstTy)
2795 return V;
2796 size_t srcSizeInBits = VectorOrPrimitiveTypeSizeInBits(srcTy);
2797 size_t dstSizeInBits = VectorOrPrimitiveTypeSizeInBits(dstTy);
2798 if (srcSizeInBits > 1 && dstSizeInBits == 1)
2799 return IRB.CreateICmpNE(V, getCleanShadow(V));
2800
2801 if (dstTy->isIntegerTy() && srcTy->isIntegerTy())
2802 return IRB.CreateIntCast(V, dstTy, Signed);
2803 if (dstTy->isVectorTy() && srcTy->isVectorTy() &&
2804 cast<VectorType>(dstTy)->getElementCount() ==
2805 cast<VectorType>(srcTy)->getElementCount())
2806 return IRB.CreateIntCast(V, dstTy, Signed);
2807 Value *V1 = IRB.CreateBitCast(V, Type::getIntNTy(*MS.C, srcSizeInBits));
2808 Value *V2 =
2809 IRB.CreateIntCast(V1, Type::getIntNTy(*MS.C, dstSizeInBits), Signed);
2810 return IRB.CreateBitCast(V2, dstTy);
2811 // TODO: handle struct types.
2812 }
2813
2814 /// Cast an application value to the type of its own shadow.
2815 Value *CreateAppToShadowCast(IRBuilder<> &IRB, Value *V) {
2816 Type *ShadowTy = getShadowTy(V);
2817 if (V->getType() == ShadowTy)
2818 return V;
2819 if (V->getType()->isPtrOrPtrVectorTy())
2820 return IRB.CreatePtrToInt(V, ShadowTy);
2821 else
2822 return IRB.CreateBitCast(V, ShadowTy);
2823 }
2824
2825 /// Propagate shadow for arbitrary operation.
2826 void handleShadowOr(Instruction &I) {
2827 IRBuilder<> IRB(&I);
2828 ShadowAndOriginCombiner SC(this, IRB);
2829 for (Use &Op : I.operands())
2830 SC.Add(Op.get());
2831 SC.Done(&I);
2832 }
2833
2834 // Perform a bitwise OR on the horizontal pairs (or other specified grouping)
2835 // of elements.
2836 //
2837 // For example, suppose we have:
2838 // VectorA: <a0, a1, a2, a3, a4, a5>
2839 // VectorB: <b0, b1, b2, b3, b4, b5>
2840 // ReductionFactor: 3
2841 // Shards: 1
2842 // The output would be:
2843 // <a0|a1|a2, a3|a4|a5, b0|b1|b2, b3|b4|b5>
2844 //
2845 // If we have:
2846 // VectorA: <a0, a1, a2, a3, a4, a5, a6, a7>
2847 // VectorB: <b0, b1, b2, b3, b4, b5, b6, b7>
2848 // ReductionFactor: 2
2849 // Shards: 2
2850 // then a and be each have 2 "shards", resulting in the output being
2851 // interleaved:
2852 // <a0|a1, a2|a3, b0|b1, b2|b3, a4|a5, a6|a7, b4|b5, b6|b7>
2853 //
2854 // This is convenient for instrumenting horizontal add/sub.
2855 // For bitwise OR on "vertical" pairs, see maybeHandleSimpleNomemIntrinsic().
2856 Value *horizontalReduce(IntrinsicInst &I, unsigned ReductionFactor,
2857 unsigned Shards, Value *VectorA, Value *VectorB) {
2858 assert(isa<FixedVectorType>(VectorA->getType()));
2859 unsigned NumElems =
2860 cast<FixedVectorType>(VectorA->getType())->getNumElements();
2861
2862 [[maybe_unused]] unsigned TotalNumElems = NumElems;
2863 if (VectorB) {
2864 assert(VectorA->getType() == VectorB->getType());
2865 TotalNumElems *= 2;
2866 }
2867
2868 assert(NumElems % (ReductionFactor * Shards) == 0);
2869
2870 Value *Or = nullptr;
2871
2872 IRBuilder<> IRB(&I);
2873 for (unsigned i = 0; i < ReductionFactor; i++) {
2874 SmallVector<int, 16> Mask;
2875
2876 for (unsigned j = 0; j < Shards; j++) {
2877 unsigned Offset = NumElems / Shards * j;
2878
2879 for (unsigned X = 0; X < NumElems / Shards; X += ReductionFactor)
2880 Mask.push_back(Offset + X + i);
2881
2882 if (VectorB) {
2883 for (unsigned X = 0; X < NumElems / Shards; X += ReductionFactor)
2884 Mask.push_back(NumElems + Offset + X + i);
2885 }
2886 }
2887
2888 Value *Masked;
2889 if (VectorB)
2890 Masked = IRB.CreateShuffleVector(VectorA, VectorB, Mask);
2891 else
2892 Masked = IRB.CreateShuffleVector(VectorA, Mask);
2893
2894 if (Or)
2895 Or = IRB.CreateOr(Or, Masked);
2896 else
2897 Or = Masked;
2898 }
2899
2900 return Or;
2901 }
2902
2903 /// Propagate shadow for 1- or 2-vector intrinsics that combine adjacent
2904 /// fields.
2905 ///
2906 /// e.g., <2 x i32> @llvm.aarch64.neon.saddlp.v2i32.v4i16(<4 x i16>)
2907 /// <16 x i8> @llvm.aarch64.neon.addp.v16i8(<16 x i8>, <16 x i8>)
2908 void handlePairwiseShadowOrIntrinsic(IntrinsicInst &I, unsigned Shards) {
2909 assert(I.arg_size() == 1 || I.arg_size() == 2);
2910
2911 assert(I.getType()->isVectorTy());
2912 assert(I.getArgOperand(0)->getType()->isVectorTy());
2913
2914 [[maybe_unused]] FixedVectorType *ParamType =
2915 cast<FixedVectorType>(I.getArgOperand(0)->getType());
2916 assert((I.arg_size() != 2) ||
2917 (ParamType == cast<FixedVectorType>(I.getArgOperand(1)->getType())));
2918 [[maybe_unused]] FixedVectorType *ReturnType =
2919 cast<FixedVectorType>(I.getType());
2920 assert(ParamType->getNumElements() * I.arg_size() ==
2921 2 * ReturnType->getNumElements());
2922
2923 IRBuilder<> IRB(&I);
2924
2925 // Horizontal OR of shadow
2926 Value *FirstArgShadow = getShadow(&I, 0);
2927 Value *SecondArgShadow = nullptr;
2928 if (I.arg_size() == 2)
2929 SecondArgShadow = getShadow(&I, 1);
2930
2931 Value *OrShadow = horizontalReduce(I, /*ReductionFactor=*/2, Shards,
2932 FirstArgShadow, SecondArgShadow);
2933
2934 OrShadow = CreateShadowCast(IRB, OrShadow, getShadowTy(&I));
2935
2936 setShadow(&I, OrShadow);
2937 setOriginForNaryOp(I);
2938 }
2939
2940 /// Propagate shadow for 1- or 2-vector intrinsics that combine adjacent
2941 /// fields, with the parameters reinterpreted to have elements of a specified
2942 /// width. For example:
2943 /// @llvm.x86.ssse3.phadd.w(<1 x i64> [[VAR1]], <1 x i64> [[VAR2]])
2944 /// conceptually operates on
2945 /// (<4 x i16> [[VAR1]], <4 x i16> [[VAR2]])
2946 /// and can be handled with ReinterpretElemWidth == 16.
2947 void handlePairwiseShadowOrIntrinsic(IntrinsicInst &I, unsigned Shards,
2948 int ReinterpretElemWidth) {
2949 assert(I.arg_size() == 1 || I.arg_size() == 2);
2950
2951 assert(I.getType()->isVectorTy());
2952 assert(I.getArgOperand(0)->getType()->isVectorTy());
2953
2954 FixedVectorType *ParamType =
2955 cast<FixedVectorType>(I.getArgOperand(0)->getType());
2956 assert((I.arg_size() != 2) ||
2957 (ParamType == cast<FixedVectorType>(I.getArgOperand(1)->getType())));
2958
2959 [[maybe_unused]] FixedVectorType *ReturnType =
2960 cast<FixedVectorType>(I.getType());
2961 assert(ParamType->getNumElements() * I.arg_size() ==
2962 2 * ReturnType->getNumElements());
2963
2964 IRBuilder<> IRB(&I);
2965
2966 FixedVectorType *ReinterpretShadowTy = nullptr;
2967 assert(isAligned(Align(ReinterpretElemWidth),
2968 ParamType->getPrimitiveSizeInBits()));
2969 ReinterpretShadowTy = FixedVectorType::get(
2970 IRB.getIntNTy(ReinterpretElemWidth),
2971 ParamType->getPrimitiveSizeInBits() / ReinterpretElemWidth);
2972
2973 // Horizontal OR of shadow
2974 Value *FirstArgShadow = getShadow(&I, 0);
2975 FirstArgShadow = IRB.CreateBitCast(FirstArgShadow, ReinterpretShadowTy);
2976
2977 // If we had two parameters each with an odd number of elements, the total
2978 // number of elements is even, but we have never seen this in extant
2979 // instruction sets, so we enforce that each parameter must have an even
2980 // number of elements.
2982 Align(2),
2983 cast<FixedVectorType>(FirstArgShadow->getType())->getNumElements()));
2984
2985 Value *SecondArgShadow = nullptr;
2986 if (I.arg_size() == 2) {
2987 SecondArgShadow = getShadow(&I, 1);
2988 SecondArgShadow = IRB.CreateBitCast(SecondArgShadow, ReinterpretShadowTy);
2989 }
2990
2991 Value *OrShadow = horizontalReduce(I, /*ReductionFactor=*/2, Shards,
2992 FirstArgShadow, SecondArgShadow);
2993
2994 OrShadow = CreateShadowCast(IRB, OrShadow, getShadowTy(&I));
2995
2996 setShadow(&I, OrShadow);
2997 setOriginForNaryOp(I);
2998 }
2999
3000 void visitFNeg(UnaryOperator &I) { handleShadowOr(I); }
3001
3002 // Handle multiplication by constant.
3003 //
3004 // Handle a special case of multiplication by constant that may have one or
3005 // more zeros in the lower bits. This makes corresponding number of lower bits
3006 // of the result zero as well. We model it by shifting the other operand
3007 // shadow left by the required number of bits. Effectively, we transform
3008 // (X * (A * 2**B)) to ((X << B) * A) and instrument (X << B) as (Sx << B).
3009 // We use multiplication by 2**N instead of shift to cover the case of
3010 // multiplication by 0, which may occur in some elements of a vector operand.
3011 void handleMulByConstant(BinaryOperator &I, Constant *ConstArg,
3012 Value *OtherArg) {
3013 Constant *ShadowMul;
3014 Type *Ty = ConstArg->getType();
3015 if (auto *VTy = dyn_cast<VectorType>(Ty)) {
3016 unsigned NumElements = cast<FixedVectorType>(VTy)->getNumElements();
3017 Type *EltTy = VTy->getElementType();
3019 for (unsigned Idx = 0; Idx < NumElements; ++Idx) {
3020 if (ConstantInt *Elt =
3022 const APInt &V = Elt->getValue();
3023 APInt V2 = APInt(V.getBitWidth(), 1) << V.countr_zero();
3024 Elements.push_back(ConstantInt::get(EltTy, V2));
3025 } else {
3026 Elements.push_back(ConstantInt::get(EltTy, 1));
3027 }
3028 }
3029 ShadowMul = ConstantVector::get(Elements);
3030 } else {
3031 if (ConstantInt *Elt = dyn_cast<ConstantInt>(ConstArg)) {
3032 const APInt &V = Elt->getValue();
3033 APInt V2 = APInt(V.getBitWidth(), 1) << V.countr_zero();
3034 ShadowMul = ConstantInt::get(Ty, V2);
3035 } else {
3036 ShadowMul = ConstantInt::get(Ty, 1);
3037 }
3038 }
3039
3040 IRBuilder<> IRB(&I);
3041 setShadow(&I,
3042 IRB.CreateMul(getShadow(OtherArg), ShadowMul, "msprop_mul_cst"));
3043 setOrigin(&I, getOrigin(OtherArg));
3044 }
3045
3046 void visitMul(BinaryOperator &I) {
3047 Constant *constOp0 = dyn_cast<Constant>(I.getOperand(0));
3048 Constant *constOp1 = dyn_cast<Constant>(I.getOperand(1));
3049 if (constOp0 && !constOp1)
3050 handleMulByConstant(I, constOp0, I.getOperand(1));
3051 else if (constOp1 && !constOp0)
3052 handleMulByConstant(I, constOp1, I.getOperand(0));
3053 else
3054 handleShadowOr(I);
3055 }
3056
3057 void visitFAdd(BinaryOperator &I) { handleShadowOr(I); }
3058 void visitFSub(BinaryOperator &I) { handleShadowOr(I); }
3059 void visitFMul(BinaryOperator &I) { handleShadowOr(I); }
3060 void visitAdd(BinaryOperator &I) { handleShadowOr(I); }
3061 void visitSub(BinaryOperator &I) { handleShadowOr(I); }
3062 void visitXor(BinaryOperator &I) { handleShadowOr(I); }
3063
3064 void handleIntegerDiv(Instruction &I) {
3065 // Strict on the second argument.
3066 insertCheckShadowOf(I.getOperand(1), &I);
3067 setShadow(&I, getShadow(&I, 0));
3068 setOrigin(&I, getOrigin(&I, 0));
3069 }
3070
3071 void visitUDiv(BinaryOperator &I) { handleIntegerDiv(I); }
3072 void visitSDiv(BinaryOperator &I) { handleIntegerDiv(I); }
3073 void visitURem(BinaryOperator &I) { handleIntegerDiv(I); }
3074 void visitSRem(BinaryOperator &I) { handleIntegerDiv(I); }
3075
3076 // Floating point division is side-effect free. We can not require that the
3077 // divisor is fully initialized and must propagate shadow. See PR37523.
3078 void visitFDiv(BinaryOperator &I) { handleShadowOr(I); }
3079 void visitFRem(BinaryOperator &I) { handleShadowOr(I); }
3080
3081 /// Instrument == and != comparisons.
3082 ///
3083 /// Sometimes the comparison result is known even if some of the bits of the
3084 /// arguments are not.
3085 void handleEqualityComparison(ICmpInst &I) {
3086 IRBuilder<> IRB(&I);
3087 Value *A = I.getOperand(0);
3088 Value *B = I.getOperand(1);
3089 Value *Sa = getShadow(A);
3090 Value *Sb = getShadow(B);
3091
3092 Value *Si = propagateEqualityComparison(IRB, A, B, Sa, Sb);
3093
3094 setShadow(&I, Si);
3095 setOriginForNaryOp(I);
3096 }
3097
3098 /// Instrument relational comparisons.
3099 ///
3100 /// This function does exact shadow propagation for all relational
3101 /// comparisons of integers, pointers and vectors of those.
3102 /// FIXME: output seems suboptimal when one of the operands is a constant
3103 void handleRelationalComparisonExact(ICmpInst &I) {
3104 IRBuilder<> IRB(&I);
3105 Value *A = I.getOperand(0);
3106 Value *B = I.getOperand(1);
3107 Value *Sa = getShadow(A);
3108 Value *Sb = getShadow(B);
3109
3110 // Get rid of pointers and vectors of pointers.
3111 // For ints (and vectors of ints), types of A and Sa match,
3112 // and this is a no-op.
3113 A = IRB.CreatePointerCast(A, Sa->getType());
3114 B = IRB.CreatePointerCast(B, Sb->getType());
3115
3116 // Let [a0, a1] be the interval of possible values of A, taking into account
3117 // its undefined bits. Let [b0, b1] be the interval of possible values of B.
3118 // Then (A cmp B) is defined iff (a0 cmp b1) == (a1 cmp b0).
3119 bool IsSigned = I.isSigned();
3120
3121 auto GetMinMaxUnsigned = [&](Value *V, Value *S) {
3122 if (IsSigned) {
3123 // Sign-flip to map from signed range to unsigned range. Relation A vs B
3124 // should be preserved, if checked with `getUnsignedPredicate()`.
3125 // Relationship between Amin, Amax, Bmin, Bmax also will not be
3126 // affected, as they are created by effectively adding/substructing from
3127 // A (or B) a value, derived from shadow, with no overflow, either
3128 // before or after sign flip.
3129 APInt MinVal =
3130 APInt::getSignedMinValue(V->getType()->getScalarSizeInBits());
3131 V = IRB.CreateXor(V, ConstantInt::get(V->getType(), MinVal));
3132 }
3133 // Minimize undefined bits.
3134 Value *Min = IRB.CreateAnd(V, IRB.CreateNot(S));
3135 Value *Max = IRB.CreateOr(V, S);
3136 return std::make_pair(Min, Max);
3137 };
3138
3139 auto [Amin, Amax] = GetMinMaxUnsigned(A, Sa);
3140 auto [Bmin, Bmax] = GetMinMaxUnsigned(B, Sb);
3141 Value *S1 = IRB.CreateICmp(I.getUnsignedPredicate(), Amin, Bmax);
3142 Value *S2 = IRB.CreateICmp(I.getUnsignedPredicate(), Amax, Bmin);
3143
3144 Value *Si = IRB.CreateXor(S1, S2);
3145 setShadow(&I, Si);
3146 setOriginForNaryOp(I);
3147 }
3148
3149 /// Instrument signed relational comparisons.
3150 ///
3151 /// Handle sign bit tests: x<0, x>=0, x<=-1, x>-1 by propagating the highest
3152 /// bit of the shadow. Everything else is delegated to handleShadowOr().
3153 void handleSignedRelationalComparison(ICmpInst &I) {
3154 Constant *constOp;
3155 Value *op = nullptr;
3157 if ((constOp = dyn_cast<Constant>(I.getOperand(1)))) {
3158 op = I.getOperand(0);
3159 pre = I.getPredicate();
3160 } else if ((constOp = dyn_cast<Constant>(I.getOperand(0)))) {
3161 op = I.getOperand(1);
3162 pre = I.getSwappedPredicate();
3163 } else {
3164 handleShadowOr(I);
3165 return;
3166 }
3167
3168 if ((constOp->isNullValue() &&
3169 (pre == CmpInst::ICMP_SLT || pre == CmpInst::ICMP_SGE)) ||
3170 (constOp->isAllOnesValue() &&
3171 (pre == CmpInst::ICMP_SGT || pre == CmpInst::ICMP_SLE))) {
3172 IRBuilder<> IRB(&I);
3173 Value *Shadow = IRB.CreateICmpSLT(getShadow(op), getCleanShadow(op),
3174 "_msprop_icmp_s");
3175 setShadow(&I, Shadow);
3176 setOrigin(&I, getOrigin(op));
3177 } else {
3178 handleShadowOr(I);
3179 }
3180 }
3181
3182 void visitICmpInst(ICmpInst &I) {
3183 if (!Opts.msan_handle_icmp) {
3184 handleShadowOr(I);
3185 return;
3186 }
3187 if (I.isEquality()) {
3188 handleEqualityComparison(I);
3189 return;
3190 }
3191
3192 assert(I.isRelational());
3193 if (Opts.msan_handle_icmp_exact) {
3194 handleRelationalComparisonExact(I);
3195 return;
3196 }
3197 if (I.isSigned()) {
3198 handleSignedRelationalComparison(I);
3199 return;
3200 }
3201
3202 assert(I.isUnsigned());
3203 if ((isa<Constant>(I.getOperand(0)) || isa<Constant>(I.getOperand(1)))) {
3204 handleRelationalComparisonExact(I);
3205 return;
3206 }
3207
3208 handleShadowOr(I);
3209 }
3210
3211 void visitFCmpInst(FCmpInst &I) { handleShadowOr(I); }
3212
3213 void handleShift(BinaryOperator &I) {
3214 IRBuilder<> IRB(&I);
3215 // If any of the S2 bits are poisoned, the whole thing is poisoned.
3216 // Otherwise perform the same shift on S1.
3217 Value *S1 = getShadow(&I, 0);
3218 Value *S2 = getShadow(&I, 1);
3219 Value *S2Conv =
3220 IRB.CreateSExt(IRB.CreateICmpNE(S2, getCleanShadow(S2)), S2->getType());
3221 Value *V2 = I.getOperand(1);
3222 Value *Shift = IRB.CreateBinOp(I.getOpcode(), S1, V2);
3223 setShadow(&I, IRB.CreateOr(Shift, S2Conv));
3224 setOriginForNaryOp(I);
3225 }
3226
3227 void visitShl(BinaryOperator &I) { handleShift(I); }
3228 void visitAShr(BinaryOperator &I) { handleShift(I); }
3229 void visitLShr(BinaryOperator &I) { handleShift(I); }
3230
3231 void handleFunnelShift(IntrinsicInst &I) {
3232 IRBuilder<> IRB(&I);
3233 // If any of the S2 bits are poisoned, the whole thing is poisoned.
3234 // Otherwise perform the same shift on S0 and S1.
3235 Value *S0 = getShadow(&I, 0);
3236 Value *S1 = getShadow(&I, 1);
3237 Value *S2 = getShadow(&I, 2);
3238 Value *S2Conv =
3239 IRB.CreateSExt(IRB.CreateICmpNE(S2, getCleanShadow(S2)), S2->getType());
3240 Value *V2 = I.getOperand(2);
3241 Value *Shift = IRB.CreateIntrinsic(I.getIntrinsicID(), S2Conv->getType(),
3242 {S0, S1, V2});
3243 setShadow(&I, IRB.CreateOr(Shift, S2Conv));
3244 setOriginForNaryOp(I);
3245 }
3246
3247 // Instrument bit manipulation intrinsics.
3248 // All of these intrinsics are Z = I(SRC, MASK)
3249 // where the types of all operands and the result match.
3250 // The following instrumentation happens to work for all of them:
3251 // Sz = I(Ssrc, MASK) | (sext (Smask != 0))
3252 void handleGenericBitManipulation(IntrinsicInst &I) {
3253 IRBuilder<> IRB(&I);
3254 Type *ShadowTy = getShadowTy(&I);
3255
3256 // If any bit of the mask operand is poisoned, then the whole thing is.
3257 Value *SMask = getShadow(&I, 1);
3258 SMask = IRB.CreateSExt(IRB.CreateICmpNE(SMask, getCleanShadow(ShadowTy)),
3259 ShadowTy);
3260 // Apply the same intrinsic to the shadow of the first operand.
3261 Value *S;
3262 if (Function *Func = I.getCalledFunction())
3263 S = IRB.CreateCall(Func, {getShadow(&I, 0), I.getOperand(1)});
3264 else
3265 S = IRB.CreateIntrinsic(I.getIntrinsicID(), ShadowTy,
3266 {getShadow(&I, 0), I.getOperand(1)});
3267
3268 setShadow(&I, IRB.CreateOr(SMask, S));
3269 setOriginForNaryOp(I);
3270 }
3271
3272 /// Instrument llvm.memmove
3273 ///
3274 /// At this point we don't know if llvm.memmove will be inlined or not.
3275 /// If we don't instrument it and it gets inlined,
3276 /// our interceptor will not kick in and we will lose the memmove.
3277 /// If we instrument the call here, but it does not get inlined,
3278 /// we will memmove the shadow twice: which is bad in case
3279 /// of overlapping regions. So, we simply lower the intrinsic to a call.
3280 ///
3281 /// Similar situation exists for memcpy and memset.
3282 void visitMemMoveInst(MemMoveInst &I) {
3283 if (handleUntrackedMemIntrinsic(I))
3284 return;
3285 getShadow(I.getArgOperand(1)); // Ensure shadow initialized
3286 IRBuilder<> IRB(&I);
3287 IRB.CreateCall(MS.MemmoveFn,
3288 {I.getArgOperand(0), I.getArgOperand(1),
3289 IRB.CreateIntCast(I.getArgOperand(2), MS.IntptrTy, false)});
3291 }
3292
3293 /// Handle a memory intrinsic that accesses memory in an address space that
3294 /// has no shadow (see isUntrackedAddrSpace). Such intrinsics cannot be
3295 /// replaced with calls into the runtime library, so leave them alone, and
3296 /// - if data is copied from untracked memory into regular memory, mark the
3297 /// destination as initialized;
3298 /// - if data is copied from regular memory into untracked memory, check the
3299 /// source eagerly (like stores into untracked memory) if its size is a
3300 /// small constant.
3301 /// Like for regular memset, the shadow of the memset value is ignored.
3302 /// Returns true if \p I was handled.
3303 bool handleUntrackedMemIntrinsic(MemIntrinsic &I) {
3304 Value *Dst = I.getRawDest();
3305 auto *MTI = dyn_cast<MemTransferInst>(&I);
3306 const bool DstUntracked = isUntrackedAddrSpace(Dst);
3307 const bool SrcUntracked = MTI && isUntrackedAddrSpace(MTI->getRawSource());
3308 if (!DstUntracked && !SrcUntracked)
3309 return false;
3310
3311 IRBuilder<> IRB(&I);
3312 if (!DstUntracked) {
3313 // __msan_unpoison_alloca() unpoisons arbitrary memory, not only allocas.
3314 unpoisonMemoryRange(IRB, Dst, I.getLength(), MS.MsanUnpoisonAllocaFn);
3315 } else if (MTI && !SrcUntracked) {
3316 checkMemoryRangeIsInitialized(IRB, MTI->getRawSource(), MTI->getLength(),
3317 &I);
3318 }
3319 return true;
3320 }
3321
3322 /// Insert a check that the \p Size bytes of memory at \p Addr are
3323 /// initialized, if \p Size is a small enough constant.
3324 void checkMemoryRangeIsInitialized(IRBuilder<> &IRB, Value *Addr, Value *Size,
3325 Instruction *OrigIns) {
3326 // Larger sizes are not checked, and the check is lost. This is
3327 // acceptable, as large copies into untracked memory are rare.
3328 constexpr uint64_t kMaxCheckedSize = 64;
3329 auto *CSize = dyn_cast<ConstantInt>(Size);
3330 if (!CSize || CSize->isZero() || CSize->getZExtValue() > kMaxCheckedSize)
3331 return;
3332 Type *ShadowTy = IRB.getIntNTy(CSize->getZExtValue() * 8);
3333 auto [ShadowPtr, OriginPtr] =
3334 getShadowOriginPtr(Addr, IRB, ShadowTy, Align(1), /*isStore*/ false);
3335 Value *Shadow = IRB.CreateAlignedLoad(ShadowTy, ShadowPtr, Align(1));
3336 Value *Origin =
3337 MS.TrackOrigins
3338 ? IRB.CreateAlignedLoad(MS.OriginTy, OriginPtr, kMinOriginAlignment)
3339 : nullptr;
3340 insertCheckShadow(Shadow, Origin, OrigIns);
3341 }
3342
3343 /// Handle an intrinsic that accesses memory through a pointer argument in an
3344 /// untracked address space (see isUntrackedAddrSpace), for which there is no
3345 /// shadow to propagate: check the arguments eagerly (only the pointers, if
3346 /// the intrinsic only reads memory), and consider the result initialized.
3347 /// Returns true if \p I was handled.
3348 bool maybeHandleUntrackedMemoryIntrinsic(IntrinsicInst &I) {
3349 if (!I.mayReadOrWriteMemory() || none_of(I.args(), [](const Use &U) {
3350 return U->getType()->isPtrOrPtrVectorTy() &&
3351 isUntrackedAddrSpace(U.get());
3352 }))
3353 return false;
3354
3355 for (const Use &U : I.args())
3356 if (U->getType()->isSized() &&
3357 (!I.onlyReadsMemory() || U->getType()->isPtrOrPtrVectorTy()))
3358 insertCheckShadowOf(U.get(), &I);
3359 setShadow(&I, getCleanShadow(&I));
3360 setOrigin(&I, getCleanOrigin());
3361 return true;
3362 }
3363
3364 /// Instrument memcpy
3365 ///
3366 /// Similar to memmove: avoid copying shadow twice. This is somewhat
3367 /// unfortunate as it may slowdown small constant memcpys.
3368 /// FIXME: consider doing manual inline for small constant sizes and proper
3369 /// alignment.
3370 ///
3371 /// Note: This also handles memcpy.inline, which promises no calls to external
3372 /// functions as an optimization. However, with instrumentation enabled this
3373 /// is difficult to promise; additionally, we know that the MSan runtime
3374 /// exists and provides __msan_memcpy(). Therefore, we assume that with
3375 /// instrumentation it's safe to turn memcpy.inline into a call to
3376 /// __msan_memcpy(). Should this be wrong, such as when implementing memcpy()
3377 /// itself, instrumentation should be disabled with the no_sanitize attribute.
3378 void visitMemCpyInst(MemCpyInst &I) {
3379 if (handleUntrackedMemIntrinsic(I))
3380 return;
3381 getShadow(I.getArgOperand(1)); // Ensure shadow initialized
3382 IRBuilder<> IRB(&I);
3383 IRB.CreateCall(MS.MemcpyFn,
3384 {I.getArgOperand(0), I.getArgOperand(1),
3385 IRB.CreateIntCast(I.getArgOperand(2), MS.IntptrTy, false)});
3387 }
3388
3389 // Same as memcpy.
3390 void visitMemSetInst(MemSetInst &I) {
3391 if (handleUntrackedMemIntrinsic(I))
3392 return;
3393 IRBuilder<> IRB(&I);
3394 IRB.CreateCall(
3395 MS.MemsetFn,
3396 {I.getArgOperand(0),
3397 IRB.CreateIntCast(I.getArgOperand(1), IRB.getInt32Ty(), false),
3398 IRB.CreateIntCast(I.getArgOperand(2), MS.IntptrTy, false)});
3400 }
3401
3402 void visitVAStartInst(VAStartInst &I) { VAHelper->visitVAStartInst(I); }
3403
3404 void visitVACopyInst(VACopyInst &I) { VAHelper->visitVACopyInst(I); }
3405
3406 /// Handle vector store-like intrinsics.
3407 ///
3408 /// Instrument intrinsics that look like a simple SIMD store: writes memory,
3409 /// has 1 pointer argument and 1 vector argument, returns void.
3410 bool handleVectorStoreIntrinsic(IntrinsicInst &I) {
3411 assert(I.arg_size() == 2);
3412
3413 IRBuilder<> IRB(&I);
3414 Value *Addr = I.getArgOperand(0);
3415 Value *Shadow = getShadow(&I, 1);
3416 Value *ShadowPtr, *OriginPtr;
3417
3418 // We don't know the pointer alignment (could be unaligned SSE store!).
3419 // Have to assume to worst case.
3420 std::tie(ShadowPtr, OriginPtr) = getShadowOriginPtr(
3421 Addr, IRB, Shadow->getType(), Align(1), /*isStore*/ true);
3422 IRB.CreateAlignedStore(Shadow, ShadowPtr, Align(1));
3423
3424 if (Opts.msan_check_access_address)
3425 insertCheckShadowOf(Addr, &I);
3426
3427 // FIXME: factor out common code from materializeStores
3428 if (MS.TrackOrigins)
3429 IRB.CreateStore(getOrigin(&I, 1), OriginPtr);
3430 return true;
3431 }
3432
3433 /// Handle vector load-like intrinsics.
3434 ///
3435 /// Instrument intrinsics that look like a simple SIMD load: reads memory,
3436 /// has 1 pointer argument, returns a vector.
3437 bool handleVectorLoadIntrinsic(IntrinsicInst &I) {
3438 assert(I.arg_size() == 1);
3439
3440 IRBuilder<> IRB(&I);
3441 Value *Addr = I.getArgOperand(0);
3442
3443 Type *ShadowTy = getShadowTy(&I);
3444 Value *ShadowPtr = nullptr, *OriginPtr = nullptr;
3445 if (PropagateShadow) {
3446 // We don't know the pointer alignment (could be unaligned SSE load!).
3447 // Have to assume to worst case.
3448 const Align Alignment = Align(1);
3449 std::tie(ShadowPtr, OriginPtr) =
3450 getShadowOriginPtr(Addr, IRB, ShadowTy, Alignment, /*isStore*/ false);
3451 setShadow(&I,
3452 IRB.CreateAlignedLoad(ShadowTy, ShadowPtr, Alignment, "_msld"));
3453 } else {
3454 setShadow(&I, getCleanShadow(&I));
3455 }
3456
3457 if (Opts.msan_check_access_address)
3458 insertCheckShadowOf(Addr, &I);
3459
3460 if (MS.TrackOrigins) {
3461 if (PropagateShadow)
3462 setOrigin(&I, IRB.CreateLoad(MS.OriginTy, OriginPtr));
3463 else
3464 setOrigin(&I, getCleanOrigin());
3465 }
3466 return true;
3467 }
3468
3469 /// Handle (SIMD arithmetic)-like intrinsics.
3470 ///
3471 /// Instrument intrinsics with any number of arguments of the same type [*],
3472 /// equal to the return type, plus a specified number of trailing flags of
3473 /// any type.
3474 ///
3475 /// [*] The type should be simple (no aggregates or pointers; vectors are
3476 /// fine).
3477 ///
3478 /// Caller guarantees that this intrinsic does not access memory.
3479 ///
3480 /// TODO: "horizontal"/"pairwise" intrinsics are often incorrectly matched by
3481 /// by this handler. See horizontalReduce().
3482 ///
3483 /// TODO: permutation intrinsics are also often incorrectly matched.
3484 [[maybe_unused]] bool
3485 maybeHandleSimpleNomemIntrinsic(IntrinsicInst &I,
3486 unsigned int trailingFlags) {
3487 Type *RetTy = I.getType();
3488 if (!(RetTy->isIntOrIntVectorTy() || RetTy->isFPOrFPVectorTy()))
3489 return false;
3490
3491 unsigned NumArgOperands = I.arg_size();
3492 assert(NumArgOperands >= trailingFlags);
3493 for (unsigned i = 0; i < NumArgOperands - trailingFlags; ++i) {
3494 Type *Ty = I.getArgOperand(i)->getType();
3495 if (Ty != RetTy)
3496 return false;
3497 }
3498
3499 IRBuilder<> IRB(&I);
3500 ShadowAndOriginCombiner SC(this, IRB);
3501 for (unsigned i = 0; i < NumArgOperands; ++i)
3502 SC.Add(I.getArgOperand(i));
3503 SC.Done(&I);
3504
3505 return true;
3506 }
3507
3508 /// Returns whether it was able to heuristically instrument unknown
3509 /// intrinsics.
3510 ///
3511 /// The main purpose of this code is to do something reasonable with all
3512 /// random intrinsics we might encounter, most importantly - SIMD intrinsics.
3513 /// We recognize several classes of intrinsics by their argument types and
3514 /// ModRefBehaviour and apply special instrumentation when we are reasonably
3515 /// sure that we know what the intrinsic does.
3516 ///
3517 /// We special-case intrinsics where this approach fails. See llvm.bswap
3518 /// handling as an example of that.
3519 bool maybeHandleUnknownIntrinsicUnlogged(IntrinsicInst &I) {
3520 unsigned NumArgOperands = I.arg_size();
3521 if (NumArgOperands == 0)
3522 return false;
3523
3524 if (NumArgOperands == 2 && I.getArgOperand(0)->getType()->isPointerTy() &&
3525 I.getArgOperand(1)->getType()->isVectorTy() &&
3526 I.getType()->isVoidTy() && !I.onlyReadsMemory()) {
3527 // This looks like a vector store.
3528 return handleVectorStoreIntrinsic(I);
3529 }
3530
3531 if (NumArgOperands == 1 && I.getArgOperand(0)->getType()->isPointerTy() &&
3532 I.getType()->isVectorTy() && I.onlyReadsMemory()) {
3533 // This looks like a vector load.
3534 return handleVectorLoadIntrinsic(I);
3535 }
3536
3537 if (I.doesNotAccessMemory())
3538 if (maybeHandleSimpleNomemIntrinsic(I, /*trailingFlags=*/0))
3539 return true;
3540
3541 // FIXME: detect and handle SSE maskstore/maskload?
3542 // Some cases are now handled in handleAVXMasked{Load,Store}.
3543 return false;
3544 }
3545
3546 bool maybeHandleUnknownIntrinsic(IntrinsicInst &I) {
3547 if (maybeHandleUnknownIntrinsicUnlogged(I)) {
3548 if (Opts.msan_dump_heuristic_instructions)
3549 dumpInst(I, "Heuristic");
3550
3551 LLVM_DEBUG(dbgs() << "UNKNOWN INSTRUCTION HANDLED HEURISTICALLY: " << I
3552 << "\n");
3553 return true;
3554 } else
3555 return false;
3556 }
3557
3558 void handleInvariantGroup(IntrinsicInst &I) {
3559 setShadow(&I, getShadow(&I, 0));
3560 setOrigin(&I, getOrigin(&I, 0));
3561 }
3562
3563 void handleLifetimeStart(IntrinsicInst &I) {
3564 if (!PoisonStack)
3565 return;
3566 AllocaInst *AI = dyn_cast<AllocaInst>(I.getArgOperand(0));
3567 if (AI)
3568 LifetimeStartList.push_back(std::make_pair(&I, AI));
3569 }
3570
3571 void handleBswap(IntrinsicInst &I) {
3572 IRBuilder<> IRB(&I);
3573 Value *Op = I.getArgOperand(0);
3574 Type *OpType = Op->getType();
3575 setShadow(&I, IRB.CreateIntrinsic(Intrinsic::bswap, ArrayRef(&OpType, 1),
3576 getShadow(Op)));
3577 setOrigin(&I, getOrigin(Op));
3578 }
3579
3580 // Uninitialized bits are ok if they appear after the leading/trailing 0's
3581 // and a 1. If the input is all zero, it is fully initialized iff
3582 // !is_zero_poison.
3583 //
3584 // e.g., for ctlz, with little-endian, if 0/1 are initialized bits with
3585 // concrete value 0/1, and ? is an uninitialized bit:
3586 // - 0001 0??? is fully initialized
3587 // - 000? ???? is fully uninitialized (*)
3588 // - ???? ???? is fully uninitialized
3589 // - 0000 0000 is fully uninitialized if is_zero_poison,
3590 // fully initialized otherwise
3591 //
3592 // (*) TODO: arguably, since the number of zeros is in the range [3, 8], we
3593 // only need to poison 4 bits.
3594 //
3595 // OutputShadow =
3596 // ((ConcreteZerosCount >= ShadowZerosCount) && !AllZeroShadow)
3597 // || (is_zero_poison && AllZeroSrc)
3598 void handleCountLeadingTrailingZeros(IntrinsicInst &I) {
3599 IRBuilder<> IRB(&I);
3600 Value *Src = I.getArgOperand(0);
3601 Value *SrcShadow = getShadow(Src);
3602
3603 Value *False = IRB.getInt1(false);
3604 Value *ConcreteZerosCount = IRB.CreateIntrinsic(
3605 I.getType(), I.getIntrinsicID(), {Src, /*is_zero_poison=*/False});
3606 Value *ShadowZerosCount = IRB.CreateIntrinsic(
3607 I.getType(), I.getIntrinsicID(), {SrcShadow, /*is_zero_poison=*/False});
3608
3609 Value *CompareConcreteZeros = IRB.CreateICmpUGE(
3610 ConcreteZerosCount, ShadowZerosCount, "_mscz_cmp_zeros");
3611
3612 Value *NotAllZeroShadow =
3613 IRB.CreateIsNotNull(SrcShadow, "_mscz_shadow_not_null");
3614 Value *OutputShadow =
3615 IRB.CreateAnd(CompareConcreteZeros, NotAllZeroShadow, "_mscz_main");
3616
3617 // If zero poison is requested, mix in with the shadow
3618 Constant *IsZeroPoison = cast<Constant>(I.getOperand(1));
3619 if (!IsZeroPoison->isNullValue()) {
3620 Value *BoolZeroPoison = IRB.CreateIsNull(Src, "_mscz_bzp");
3621 OutputShadow = IRB.CreateOr(OutputShadow, BoolZeroPoison, "_mscz_bs");
3622 }
3623
3624 OutputShadow = IRB.CreateSExt(OutputShadow, getShadowTy(Src), "_mscz_os");
3625
3626 setShadow(&I, OutputShadow);
3627 setOriginForNaryOp(I);
3628 }
3629
3630 /// Some instructions have additional zero-elements in the return type
3631 /// e.g., <16 x i8> @llvm.x86.avx512.mask.pmov.qb.512(<8 x i64>, ...)
3632 ///
3633 /// This function will return a vector type with the same number of elements
3634 /// as the input, but same per-element width as the return value e.g.,
3635 /// <8 x i8>.
3636 FixedVectorType *maybeShrinkVectorShadowType(Value *Src, IntrinsicInst &I) {
3637 assert(isa<FixedVectorType>(getShadowTy(&I)));
3638 FixedVectorType *ShadowType = cast<FixedVectorType>(getShadowTy(&I));
3639
3640 // TODO: generalize beyond 2x?
3641 if (ShadowType->getElementCount() ==
3642 cast<VectorType>(Src->getType())->getElementCount() * 2)
3643 ShadowType = FixedVectorType::getHalfElementsVectorType(ShadowType);
3644
3645 assert(ShadowType->getElementCount() ==
3646 cast<VectorType>(Src->getType())->getElementCount());
3647
3648 return ShadowType;
3649 }
3650
3651 /// Doubles the length of a vector shadow (extending with zeros) if necessary
3652 /// to match the length of the shadow for the instruction.
3653 /// If scalar types of the vectors are different, it will use the type of the
3654 /// input vector.
3655 /// This is more type-safe than CreateShadowCast().
3656 Value *maybeExtendVectorShadowWithZeros(Value *Shadow, IntrinsicInst &I) {
3657 IRBuilder<> IRB(&I);
3659 assert(isa<FixedVectorType>(I.getType()));
3660
3661 Value *FullShadow = getCleanShadow(&I);
3662 unsigned ShadowNumElems =
3663 cast<FixedVectorType>(Shadow->getType())->getNumElements();
3664 unsigned FullShadowNumElems =
3665 cast<FixedVectorType>(FullShadow->getType())->getNumElements();
3666
3667 assert((ShadowNumElems == FullShadowNumElems) ||
3668 (ShadowNumElems * 2 == FullShadowNumElems));
3669
3670 if (ShadowNumElems == FullShadowNumElems) {
3671 FullShadow = Shadow;
3672 } else {
3673 // TODO: generalize beyond 2x?
3674 SmallVector<int, 32> ShadowMask(FullShadowNumElems);
3675 std::iota(ShadowMask.begin(), ShadowMask.end(), 0);
3676
3677 // Append zeros
3678 FullShadow =
3679 IRB.CreateShuffleVector(Shadow, getCleanShadow(Shadow), ShadowMask);
3680 }
3681
3682 return FullShadow;
3683 }
3684
3685 /// Handle x86 SSE vector conversion.
3686 ///
3687 /// e.g., single-precision to half-precision conversion:
3688 /// <8 x i16> @llvm.x86.vcvtps2ph.256(<8 x float> %a0, i32 0)
3689 /// <8 x i16> @llvm.x86.vcvtps2ph.128(<4 x float> %a0, i32 0)
3690 ///
3691 /// floating-point to integer:
3692 /// <4 x i32> @llvm.x86.sse2.cvtps2dq(<4 x float>)
3693 /// <4 x i32> @llvm.x86.sse2.cvtpd2dq(<2 x double>)
3694 ///
3695 /// Note: if the output has more elements, they are zero-initialized (and
3696 /// therefore the shadow will also be initialized).
3697 ///
3698 /// This differs from handleSSEVectorConvertIntrinsic() because it
3699 /// propagates uninitialized shadow (instead of checking the shadow).
3700 void handleSSEVectorConvertIntrinsicByProp(IntrinsicInst &I,
3701 bool HasRoundingMode) {
3702 if (HasRoundingMode) {
3703 assert(I.arg_size() == 2);
3704 [[maybe_unused]] Value *RoundingMode = I.getArgOperand(1);
3705 assert(RoundingMode->getType()->isIntegerTy());
3706 } else {
3707 assert(I.arg_size() == 1);
3708 }
3709
3710 Value *Src = I.getArgOperand(0);
3711 assert(Src->getType()->isVectorTy());
3712
3713 // The return type might have more elements than the input.
3714 // Temporarily shrink the return type's number of elements.
3715 VectorType *ShadowType = maybeShrinkVectorShadowType(Src, I);
3716
3717 IRBuilder<> IRB(&I);
3718 Value *S0 = getShadow(&I, 0);
3719
3720 /// For scalars:
3721 /// Since they are converting to and/or from floating-point, the output is:
3722 /// - fully uninitialized if *any* bit of the input is uninitialized
3723 /// - fully ininitialized if all bits of the input are ininitialized
3724 /// We apply the same principle on a per-field basis for vectors.
3725 Value *Shadow =
3726 IRB.CreateSExt(IRB.CreateICmpNE(S0, getCleanShadow(S0)), ShadowType);
3727
3728 // The return type might have more elements than the input.
3729 // Extend the return type back to its original width if necessary.
3730 Value *FullShadow = maybeExtendVectorShadowWithZeros(Shadow, I);
3731
3732 setShadow(&I, FullShadow);
3733 setOriginForNaryOp(I);
3734 }
3735
3736 // Instrument x86 SSE vector convert intrinsic.
3737 //
3738 // This function instruments intrinsics like cvtsi2ss:
3739 // %Out = int_xxx_cvtyyy(%ConvertOp)
3740 // or
3741 // %Out = int_xxx_cvtyyy(%CopyOp, %ConvertOp)
3742 // Intrinsic converts \p NumUsedElements elements of \p ConvertOp to the same
3743 // number \p Out elements, and (if has 2 arguments) copies the rest of the
3744 // elements from \p CopyOp.
3745 // In most cases conversion involves floating-point value which may trigger a
3746 // hardware exception when not fully initialized. For this reason we require
3747 // \p ConvertOp[0:NumUsedElements] to be fully initialized and trap otherwise.
3748 // We copy the shadow of \p CopyOp[NumUsedElements:] to \p
3749 // Out[NumUsedElements:]. This means that intrinsics without \p CopyOp always
3750 // return a fully initialized value.
3751 //
3752 // For Arm NEON vector convert intrinsics, see
3753 // handleNEONVectorConvertIntrinsic().
3754 void handleSSEVectorConvertIntrinsic(IntrinsicInst &I, int NumUsedElements,
3755 bool HasRoundingMode = false) {
3756 IRBuilder<> IRB(&I);
3757 Value *CopyOp, *ConvertOp;
3758
3759 assert((!HasRoundingMode ||
3760 isa<ConstantInt>(I.getArgOperand(I.arg_size() - 1))) &&
3761 "Invalid rounding mode");
3762
3763 switch (I.arg_size() - HasRoundingMode) {
3764 case 2:
3765 CopyOp = I.getArgOperand(0);
3766 ConvertOp = I.getArgOperand(1);
3767 break;
3768 case 1:
3769 ConvertOp = I.getArgOperand(0);
3770 CopyOp = nullptr;
3771 break;
3772 default:
3773 llvm_unreachable("Cvt intrinsic with unsupported number of arguments.");
3774 }
3775
3776 // The first *NumUsedElements* elements of ConvertOp are converted to the
3777 // same number of output elements. The rest of the output is copied from
3778 // CopyOp, or (if not available) filled with zeroes.
3779 // Combine shadow for elements of ConvertOp that are used in this operation,
3780 // and insert a check.
3781 // FIXME: consider propagating shadow of ConvertOp, at least in the case of
3782 // int->any conversion.
3783 Value *ConvertShadow = getShadow(ConvertOp);
3784 Value *AggShadow = nullptr;
3785 if (ConvertOp->getType()->isVectorTy()) {
3786 AggShadow = IRB.CreateExtractElement(
3787 ConvertShadow, ConstantInt::get(IRB.getInt32Ty(), 0));
3788 for (int i = 1; i < NumUsedElements; ++i) {
3789 Value *MoreShadow = IRB.CreateExtractElement(
3790 ConvertShadow, ConstantInt::get(IRB.getInt32Ty(), i));
3791 AggShadow = IRB.CreateOr(AggShadow, MoreShadow);
3792 }
3793 } else {
3794 AggShadow = ConvertShadow;
3795 }
3796 assert(AggShadow->getType()->isIntegerTy());
3797 insertCheckShadow(AggShadow, getOrigin(ConvertOp), &I);
3798
3799 // Build result shadow by zero-filling parts of CopyOp shadow that come from
3800 // ConvertOp.
3801 if (CopyOp) {
3802 assert(CopyOp->getType() == I.getType());
3803 assert(CopyOp->getType()->isVectorTy());
3804 Value *ResultShadow = getShadow(CopyOp);
3805 Type *EltTy = cast<VectorType>(ResultShadow->getType())->getElementType();
3806 for (int i = 0; i < NumUsedElements; ++i) {
3807 ResultShadow = IRB.CreateInsertElement(
3808 ResultShadow, ConstantInt::getNullValue(EltTy),
3809 ConstantInt::get(IRB.getInt32Ty(), i));
3810 }
3811 setShadow(&I, ResultShadow);
3812 setOrigin(&I, getOrigin(CopyOp));
3813 } else {
3814 setShadow(&I, getCleanShadow(&I));
3815 setOrigin(&I, getCleanOrigin());
3816 }
3817 }
3818
3819 // Given a scalar or vector, extract lower 64 bits (or less), and return all
3820 // zeroes if it is zero, and all ones otherwise.
3821 Value *Lower64ShadowExtend(IRBuilder<> &IRB, Value *S, Type *T) {
3822 if (S->getType()->isVectorTy())
3823 S = CreateShadowCast(IRB, S, IRB.getInt64Ty(), /* Signed */ true);
3824 assert(S->getType()->getPrimitiveSizeInBits() <= 64);
3825 Value *S2 = IRB.CreateICmpNE(S, getCleanShadow(S));
3826 return CreateShadowCast(IRB, S2, T, /* Signed */ true);
3827 }
3828
3829 // Given a vector, extract its first element, and return all
3830 // zeroes if it is zero, and all ones otherwise.
3831 Value *LowerElementShadowExtend(IRBuilder<> &IRB, Value *S, Type *T) {
3832 Value *S1 = IRB.CreateExtractElement(S, (uint64_t)0);
3833 Value *S2 = IRB.CreateICmpNE(S1, getCleanShadow(S1));
3834 return CreateShadowCast(IRB, S2, T, /* Signed */ true);
3835 }
3836
3837 Value *VariableShadowExtend(IRBuilder<> &IRB, Value *S) {
3838 Type *T = S->getType();
3839 assert(T->isVectorTy());
3840 Value *S2 = IRB.CreateICmpNE(S, getCleanShadow(S));
3841 return IRB.CreateSExt(S2, T);
3842 }
3843
3844 // Instrument vector shift intrinsic.
3845 //
3846 // This function instruments intrinsics like int_x86_avx2_psll_w.
3847 // Intrinsic shifts %In by %ShiftSize bits.
3848 // %ShiftSize may be a vector. In that case the lower 64 bits determine shift
3849 // size, and the rest is ignored. Behavior is defined even if shift size is
3850 // greater than register (or field) width.
3851 void handleVectorShiftIntrinsic(IntrinsicInst &I, bool Variable) {
3852 assert(I.arg_size() == 2);
3853 IRBuilder<> IRB(&I);
3854 // If any of the S2 bits are poisoned, the whole thing is poisoned.
3855 // Otherwise perform the same shift on S1.
3856 Value *S1 = getShadow(&I, 0);
3857 Value *S2 = getShadow(&I, 1);
3858 Value *S2Conv = Variable ? VariableShadowExtend(IRB, S2)
3859 : Lower64ShadowExtend(IRB, S2, getShadowTy(&I));
3860 Value *V1 = I.getOperand(0);
3861 Value *V2 = I.getOperand(1);
3862 Value *Shift = IRB.CreateCall(I.getFunctionType(), I.getCalledOperand(),
3863 {IRB.CreateBitCast(S1, V1->getType()), V2});
3864 Shift = IRB.CreateBitCast(Shift, getShadowTy(&I));
3865 setShadow(&I, IRB.CreateOr(Shift, S2Conv));
3866 setOriginForNaryOp(I);
3867 }
3868
3869 // Get an MMX-sized (64-bit) vector type, or optionally, other sized
3870 // vectors.
3871 Type *getMMXVectorTy(unsigned EltSizeInBits,
3872 unsigned X86_MMXSizeInBits = 64) {
3873 assert(EltSizeInBits != 0 && (X86_MMXSizeInBits % EltSizeInBits) == 0 &&
3874 "Illegal MMX vector element size");
3875 return FixedVectorType::get(IntegerType::get(*MS.C, EltSizeInBits),
3876 X86_MMXSizeInBits / EltSizeInBits);
3877 }
3878
3879 // Returns a signed counterpart for an (un)signed-saturate-and-pack
3880 // intrinsic.
3881 Intrinsic::ID getSignedPackIntrinsic(Intrinsic::ID id) {
3882 switch (id) {
3883 case Intrinsic::x86_sse2_packsswb_128:
3884 case Intrinsic::x86_sse2_packuswb_128:
3885 return Intrinsic::x86_sse2_packsswb_128;
3886
3887 case Intrinsic::x86_sse2_packssdw_128:
3888 case Intrinsic::x86_sse41_packusdw:
3889 return Intrinsic::x86_sse2_packssdw_128;
3890
3891 case Intrinsic::x86_avx2_packsswb:
3892 case Intrinsic::x86_avx2_packuswb:
3893 return Intrinsic::x86_avx2_packsswb;
3894
3895 case Intrinsic::x86_avx2_packssdw:
3896 case Intrinsic::x86_avx2_packusdw:
3897 return Intrinsic::x86_avx2_packssdw;
3898
3899 case Intrinsic::x86_mmx_packsswb:
3900 case Intrinsic::x86_mmx_packuswb:
3901 return Intrinsic::x86_mmx_packsswb;
3902
3903 case Intrinsic::x86_mmx_packssdw:
3904 return Intrinsic::x86_mmx_packssdw;
3905
3906 case Intrinsic::x86_avx512_packssdw_512:
3907 case Intrinsic::x86_avx512_packusdw_512:
3908 return Intrinsic::x86_avx512_packssdw_512;
3909
3910 case Intrinsic::x86_avx512_packsswb_512:
3911 case Intrinsic::x86_avx512_packuswb_512:
3912 return Intrinsic::x86_avx512_packsswb_512;
3913
3914 default:
3915 llvm_unreachable("unexpected intrinsic id");
3916 }
3917 }
3918
3919 // Instrument vector pack intrinsic.
3920 //
3921 // This function instruments intrinsics like x86_mmx_packsswb, that
3922 // packs elements of 2 input vectors into half as many bits with saturation.
3923 // Shadow is propagated with the signed variant of the same intrinsic applied
3924 // to sext(Sa != zeroinitializer), sext(Sb != zeroinitializer).
3925 // MMXEltSizeInBits is used only for x86mmx arguments.
3926 //
3927 // TODO: consider using GetMinMaxUnsigned() to handle saturation precisely
3928 void handleVectorPackIntrinsic(IntrinsicInst &I,
3929 unsigned MMXEltSizeInBits = 0) {
3930 assert(I.arg_size() == 2);
3931 IRBuilder<> IRB(&I);
3932 Value *S1 = getShadow(&I, 0);
3933 Value *S2 = getShadow(&I, 1);
3934 assert(S1->getType()->isVectorTy());
3935
3936 // SExt and ICmpNE below must apply to individual elements of input vectors.
3937 // In case of x86mmx arguments, cast them to appropriate vector types and
3938 // back.
3939 Type *T =
3940 MMXEltSizeInBits ? getMMXVectorTy(MMXEltSizeInBits) : S1->getType();
3941 if (MMXEltSizeInBits) {
3942 S1 = IRB.CreateBitCast(S1, T);
3943 S2 = IRB.CreateBitCast(S2, T);
3944 }
3945 Value *S1_ext =
3947 Value *S2_ext =
3949 if (MMXEltSizeInBits) {
3950 S1_ext = IRB.CreateBitCast(S1_ext, getMMXVectorTy(64));
3951 S2_ext = IRB.CreateBitCast(S2_ext, getMMXVectorTy(64));
3952 }
3953
3954 Value *S = IRB.CreateIntrinsic(getSignedPackIntrinsic(I.getIntrinsicID()),
3955 {S1_ext, S2_ext}, /*FMFSource=*/nullptr,
3956 "_msprop_vector_pack");
3957 if (MMXEltSizeInBits)
3958 S = IRB.CreateBitCast(S, getShadowTy(&I));
3959 setShadow(&I, S);
3960 setOriginForNaryOp(I);
3961 }
3962
3963 // Convert `Mask` into `<n x i1>`.
3964 Constant *createDppMask(unsigned Width, unsigned Mask) {
3965 SmallVector<Constant *, 4> R(Width);
3966 for (auto &M : R) {
3967 M = ConstantInt::getBool(F.getContext(), Mask & 1);
3968 Mask >>= 1;
3969 }
3970 return ConstantVector::get(R);
3971 }
3972
3973 // Calculate output shadow as array of booleans `<n x i1>`, assuming if any
3974 // arg is poisoned, entire dot product is poisoned.
3975 Value *findDppPoisonedOutput(IRBuilder<> &IRB, Value *S, unsigned SrcMask,
3976 unsigned DstMask) {
3977 const unsigned Width =
3978 cast<FixedVectorType>(S->getType())->getNumElements();
3979
3980 S = IRB.CreateSelect(createDppMask(Width, SrcMask), S,
3982 Value *SElem = IRB.CreateOrReduce(S);
3983 Value *IsClean = IRB.CreateIsNull(SElem, "_msdpp");
3984 Value *DstMaskV = createDppMask(Width, DstMask);
3985
3986 return IRB.CreateSelect(
3987 IsClean, Constant::getNullValue(DstMaskV->getType()), DstMaskV);
3988 }
3989
3990 // See `Intel Intrinsics Guide` for `_dp_p*` instructions.
3991 //
3992 // 2 and 4 element versions produce single scalar of dot product, and then
3993 // puts it into elements of output vector, selected by 4 lowest bits of the
3994 // mask. Top 4 bits of the mask control which elements of input to use for dot
3995 // product.
3996 //
3997 // 8 element version mask still has only 4 bit for input, and 4 bit for output
3998 // mask. According to the spec it just operates as 4 element version on first
3999 // 4 elements of inputs and output, and then on last 4 elements of inputs and
4000 // output.
4001 void handleDppIntrinsic(IntrinsicInst &I) {
4002 IRBuilder<> IRB(&I);
4003
4004 Value *S0 = getShadow(&I, 0);
4005 Value *S1 = getShadow(&I, 1);
4006 Value *S = IRB.CreateOr(S0, S1);
4007
4008 const unsigned Width =
4009 cast<FixedVectorType>(S->getType())->getNumElements();
4010 assert(Width == 2 || Width == 4 || Width == 8);
4011
4012 const unsigned Mask = cast<ConstantInt>(I.getArgOperand(2))->getZExtValue();
4013 const unsigned SrcMask = Mask >> 4;
4014 const unsigned DstMask = Mask & 0xf;
4015
4016 // Calculate shadow as `<n x i1>`.
4017 Value *SI1 = findDppPoisonedOutput(IRB, S, SrcMask, DstMask);
4018 if (Width == 8) {
4019 // First 4 elements of shadow are already calculated. `makeDppShadow`
4020 // operats on 32 bit masks, so we can just shift masks, and repeat.
4021 SI1 = IRB.CreateOr(
4022 SI1, findDppPoisonedOutput(IRB, S, SrcMask << 4, DstMask << 4));
4023 }
4024 // Extend to real size of shadow, poisoning either all or none bits of an
4025 // element.
4026 S = IRB.CreateSExt(SI1, S->getType(), "_msdpp");
4027
4028 setShadow(&I, S);
4029 setOriginForNaryOp(I);
4030 }
4031
4032 Value *convertBlendvToSelectMask(IRBuilder<> &IRB, Value *C) {
4033 C = CreateAppToShadowCast(IRB, C);
4034 FixedVectorType *FVT = cast<FixedVectorType>(C->getType());
4035 unsigned ElSize = FVT->getElementType()->getPrimitiveSizeInBits();
4036 C = IRB.CreateAShr(C, ElSize - 1);
4037 FVT = FixedVectorType::get(IRB.getInt1Ty(), FVT->getNumElements());
4038 return IRB.CreateTrunc(C, FVT);
4039 }
4040
4041 // `blendv(f, t, c)` is effectively `select(c[top_bit], t, f)`.
4042 void handleBlendvIntrinsic(IntrinsicInst &I) {
4043 Value *C = I.getOperand(2);
4044 Value *T = I.getOperand(1);
4045 Value *F = I.getOperand(0);
4046
4047 Value *Sc = getShadow(&I, 2);
4048 Value *Oc = MS.TrackOrigins ? getOrigin(C) : nullptr;
4049
4050 {
4051 IRBuilder<> IRB(&I);
4052 // Extract top bit from condition and its shadow.
4053 C = convertBlendvToSelectMask(IRB, C);
4054 Sc = convertBlendvToSelectMask(IRB, Sc);
4055
4056 setShadow(C, Sc);
4057 setOrigin(C, Oc);
4058 }
4059
4060 handleSelectLikeInst(I, C, T, F);
4061 }
4062
4063 // Instrument sum-of-absolute-differences intrinsic.
4064 void handleVectorSadIntrinsic(IntrinsicInst &I, bool IsMMX = false) {
4065 const unsigned SignificantBitsPerResultElement = 16;
4066 Type *ResTy = IsMMX ? IntegerType::get(*MS.C, 64) : I.getType();
4067 unsigned ZeroBitsPerResultElement =
4068 ResTy->getScalarSizeInBits() - SignificantBitsPerResultElement;
4069
4070 IRBuilder<> IRB(&I);
4071 auto *Shadow0 = getShadow(&I, 0);
4072 auto *Shadow1 = getShadow(&I, 1);
4073 Value *S = IRB.CreateOr(Shadow0, Shadow1);
4074 S = IRB.CreateBitCast(S, ResTy);
4075 S = IRB.CreateSExt(IRB.CreateICmpNE(S, Constant::getNullValue(ResTy)),
4076 ResTy);
4077 S = IRB.CreateLShr(S, ZeroBitsPerResultElement);
4078 S = IRB.CreateBitCast(S, getShadowTy(&I));
4079 setShadow(&I, S);
4080 setOriginForNaryOp(I);
4081 }
4082
4083 // Instrument dot-product / multiply-add(-accumulate)? intrinsics.
4084 //
4085 // e.g., Two operands:
4086 // <4 x i32> @llvm.x86.sse2.pmadd.wd(<8 x i16> %a, <8 x i16> %b)
4087 //
4088 // Two operands which require an EltSizeInBits override:
4089 // <1 x i64> @llvm.x86.mmx.pmadd.wd(<1 x i64> %a, <1 x i64> %b)
4090 //
4091 // Three operands:
4092 // <4 x i32> @llvm.x86.avx512.vpdpbusd.128
4093 // (<4 x i32> %s, <16 x i8> %a, <16 x i8> %b)
4094 // <2 x float> @llvm.aarch64.neon.bfdot.v2f32.v4bf16
4095 // (<2 x float> %acc, <4 x bfloat> %a, <4 x bfloat> %b)
4096 // (these are equivalent to multiply-add on %a and %b, followed by
4097 // adding/"accumulating" %s. "Accumulation" stores the result in one
4098 // of the source registers, but this accumulate vs. add distinction
4099 // is lost when dealing with LLVM intrinsics.)
4100 //
4101 // ZeroPurifies means that multiplying a known-zero with an uninitialized
4102 // value results in an initialized value. This is applicable for integer
4103 // multiplication, but not floating-point (counter-example: NaN).
4104 void handleVectorDotProductIntrinsic(IntrinsicInst &I,
4105 unsigned ReductionFactor,
4106 bool ZeroPurifies,
4107 unsigned EltSizeInBits,
4108 enum OddOrEvenLanes Lanes) {
4109 IRBuilder<> IRB(&I);
4110
4111 [[maybe_unused]] FixedVectorType *ReturnType =
4112 cast<FixedVectorType>(I.getType());
4113 assert(isa<FixedVectorType>(ReturnType));
4114
4115 // Vectors A and B, and shadows
4116 Value *Va = nullptr;
4117 Value *Vb = nullptr;
4118 Value *Sa = nullptr;
4119 Value *Sb = nullptr;
4120
4121 assert(I.arg_size() == 2 || I.arg_size() == 3);
4122 if (I.arg_size() == 2) {
4123 assert(Lanes == kBothLanes);
4124
4125 Va = I.getOperand(0);
4126 Vb = I.getOperand(1);
4127
4128 Sa = getShadow(&I, 0);
4129 Sb = getShadow(&I, 1);
4130 } else if (I.arg_size() == 3) {
4131 // Operand 0 is the accumulator. We will deal with that below.
4132 Va = I.getOperand(1);
4133 Vb = I.getOperand(2);
4134
4135 Sa = getShadow(&I, 1);
4136 Sb = getShadow(&I, 2);
4137
4138 if (Lanes == kEvenLanes || Lanes == kOddLanes) {
4139 // Convert < S0, S1, S2, S3, S4, S5, S6, S7 >
4140 // to < S0, S0, S2, S2, S4, S4, S6, S6 > (if even)
4141 // to < S1, S1, S3, S3, S5, S5, S7, S7 > (if odd)
4142 //
4143 // Note: for aarch64.neon.bfmlalb/t, the odd/even-indexed values are
4144 // zeroed, not duplicated. However, for shadow propagation, this
4145 // distinction is unimportant because Step 1 below will squeeze
4146 // each pair of elements (e.g., [S0, S0]) into a single bit, and
4147 // we only care if it is fully initialized.
4148
4149 FixedVectorType *InputShadowType = cast<FixedVectorType>(Sa->getType());
4150 unsigned Width = InputShadowType->getNumElements();
4151
4152 Sa = IRB.CreateShuffleVector(
4153 Sa, getPclmulMask(Width, /*OddElements=*/Lanes == kOddLanes));
4154 Sb = IRB.CreateShuffleVector(
4155 Sb, getPclmulMask(Width, /*OddElements=*/Lanes == kOddLanes));
4156 }
4157 }
4158
4159 FixedVectorType *ParamType = cast<FixedVectorType>(Va->getType());
4160 assert(ParamType == Vb->getType());
4161
4162 assert(ParamType->getPrimitiveSizeInBits() ==
4163 ReturnType->getPrimitiveSizeInBits());
4164
4165 if (I.arg_size() == 3) {
4166 [[maybe_unused]] auto *AccumulatorType =
4167 cast<FixedVectorType>(I.getOperand(0)->getType());
4168 assert(AccumulatorType == ReturnType);
4169 }
4170
4171 FixedVectorType *ImplicitReturnType =
4172 cast<FixedVectorType>(getShadowTy(ReturnType));
4173 // Step 1: instrument multiplication of corresponding vector elements
4174 if (EltSizeInBits) {
4175 ImplicitReturnType = cast<FixedVectorType>(
4176 getMMXVectorTy(EltSizeInBits * ReductionFactor,
4177 ParamType->getPrimitiveSizeInBits()));
4178 ParamType = cast<FixedVectorType>(
4179 getMMXVectorTy(EltSizeInBits, ParamType->getPrimitiveSizeInBits()));
4180
4181 Va = IRB.CreateBitCast(Va, ParamType);
4182 Vb = IRB.CreateBitCast(Vb, ParamType);
4183
4184 Sa = IRB.CreateBitCast(Sa, getShadowTy(ParamType));
4185 Sb = IRB.CreateBitCast(Sb, getShadowTy(ParamType));
4186 } else {
4187 assert(ParamType->getNumElements() ==
4188 ReturnType->getNumElements() * ReductionFactor);
4189 }
4190
4191 // Each element of the vector is represented by a single bit (poisoned or
4192 // not) e.g., <8 x i1>.
4193 Value *SaNonZero = IRB.CreateIsNotNull(Sa);
4194 Value *SbNonZero = IRB.CreateIsNotNull(Sb);
4195 Value *And;
4196 if (ZeroPurifies) {
4197 // Multiplying an *initialized* zero by an uninitialized element results
4198 // in an initialized zero element.
4199 //
4200 // This is analogous to bitwise AND, where "AND" of 0 and a poisoned value
4201 // results in an unpoisoned value.
4202 Value *VaInt = Va;
4203 Value *VbInt = Vb;
4204 if (!Va->getType()->isIntegerTy()) {
4205 VaInt = CreateAppToShadowCast(IRB, Va);
4206 VbInt = CreateAppToShadowCast(IRB, Vb);
4207 }
4208
4209 // We check for non-zero on a per-element basis, not per-bit.
4210 Value *VaNonZero = IRB.CreateIsNotNull(VaInt);
4211 Value *VbNonZero = IRB.CreateIsNotNull(VbInt);
4212
4213 And = handleBitwiseAnd(IRB, VaNonZero, VbNonZero, SaNonZero, SbNonZero);
4214 } else {
4215 And = IRB.CreateOr({SaNonZero, SbNonZero});
4216 }
4217
4218 // Extend <8 x i1> to <8 x i16>.
4219 // (The real pmadd intrinsic would have computed intermediate values of
4220 // <8 x i32>, but that is irrelevant for our shadow purposes because we
4221 // consider each element to be either fully initialized or fully
4222 // uninitialized.)
4223 And = IRB.CreateSExt(And, Sa->getType());
4224
4225 // Step 2: instrument horizontal add
4226 // We don't need bit-precise horizontalReduce because we only want to check
4227 // if each pair/quad of elements is fully zero.
4228 // Cast to <4 x i32>.
4229 Value *Horizontal = IRB.CreateBitCast(And, ImplicitReturnType);
4230
4231 // Compute <4 x i1>, then extend back to <4 x i32>.
4232 Value *OutShadow = IRB.CreateSExt(
4233 IRB.CreateICmpNE(Horizontal,
4234 Constant::getNullValue(Horizontal->getType())),
4235 ImplicitReturnType);
4236
4237 // Cast it back to the required fake return type (if MMX: <1 x i64>; for
4238 // AVX, it is already correct).
4239 if (EltSizeInBits)
4240 OutShadow = CreateShadowCast(IRB, OutShadow, getShadowTy(&I));
4241
4242 // Step 3 (if applicable): instrument accumulator
4243 if (I.arg_size() == 3)
4244 OutShadow = IRB.CreateOr(OutShadow, getShadow(&I, 0));
4245
4246 setShadow(&I, OutShadow);
4247 setOriginForNaryOp(I);
4248 }
4249
4250 // Instrument compare-packed intrinsic.
4251 //
4252 // x86 has the predicate as the third operand, which is ImmArg e.g.,
4253 // - <4 x double> @llvm.x86.avx.cmp.pd.256(<4 x double>, <4 x double>, i8)
4254 // - <2 x double> @llvm.x86.sse2.cmp.pd(<2 x double>, <2 x double>, i8)
4255 //
4256 // while Arm has separate intrinsics for >= and > e.g.,
4257 // - <2 x i32> @llvm.aarch64.neon.facge.v2i32.v2f32
4258 // (<2 x float> %A, <2 x float>)
4259 // - <2 x i32> @llvm.aarch64.neon.facgt.v2i32.v2f32
4260 // (<2 x float> %A, <2 x float>)
4261 //
4262 // Bonus: this also handles scalar cases e.g.,
4263 // - i32 @llvm.aarch64.neon.facgt.i32.f32(float %A, float %B)
4264 void handleVectorComparePackedIntrinsic(IntrinsicInst &I,
4265 bool PredicateAsOperand) {
4266 if (PredicateAsOperand) {
4267 assert(I.arg_size() == 3);
4268 assert(I.paramHasAttr(2, Attribute::ImmArg));
4269 } else
4270 assert(I.arg_size() == 2);
4271
4272 IRBuilder<> IRB(&I);
4273
4274 // Basically, an or followed by sext(icmp ne 0) to end up with all-zeros or
4275 // all-ones shadow.
4276 Type *ResTy = getShadowTy(&I);
4277 auto *Shadow0 = getShadow(&I, 0);
4278 auto *Shadow1 = getShadow(&I, 1);
4279 Value *S0 = IRB.CreateOr(Shadow0, Shadow1);
4280 Value *S = IRB.CreateSExt(
4281 IRB.CreateICmpNE(S0, Constant::getNullValue(ResTy)), ResTy);
4282 setShadow(&I, S);
4283 setOriginForNaryOp(I);
4284 }
4285
4286 // Instrument compare-scalar intrinsic.
4287 // This handles both cmp* intrinsics which return the result in the first
4288 // element of a vector, and comi* which return the result as i32.
4289 void handleVectorCompareScalarIntrinsic(IntrinsicInst &I) {
4290 IRBuilder<> IRB(&I);
4291 auto *Shadow0 = getShadow(&I, 0);
4292 auto *Shadow1 = getShadow(&I, 1);
4293 Value *S0 = IRB.CreateOr(Shadow0, Shadow1);
4294 Value *S = LowerElementShadowExtend(IRB, S0, getShadowTy(&I));
4295 setShadow(&I, S);
4296 setOriginForNaryOp(I);
4297 }
4298
4299 // Instrument generic vector reduction intrinsics
4300 // by ORing together all their fields.
4301 //
4302 // If AllowShadowCast is true, the return type does not need to be the same
4303 // type as the fields
4304 // e.g., declare i32 @llvm.aarch64.neon.uaddv.i32.v16i8(<16 x i8>)
4305 void handleVectorReduceIntrinsic(IntrinsicInst &I, bool AllowShadowCast) {
4306 assert(I.arg_size() == 1);
4307
4308 IRBuilder<> IRB(&I);
4309 Value *S = IRB.CreateOrReduce(getShadow(&I, 0));
4310 if (AllowShadowCast)
4311 S = CreateShadowCast(IRB, S, getShadowTy(&I));
4312 else
4313 assert(S->getType() == getShadowTy(&I));
4314 setShadow(&I, S);
4315 setOriginForNaryOp(I);
4316 }
4317
4318 // Similar to handleVectorReduceIntrinsic but with an initial starting value.
4319 // e.g., call float @llvm.vector.reduce.fadd.f32.v2f32(float %a0, <2 x float>
4320 // %a1)
4321 // shadow = shadow[a0] | shadow[a1.0] | shadow[a1.1]
4322 //
4323 // The type of the return value, initial starting value, and elements of the
4324 // vector must be identical.
4325 void handleVectorReduceWithStarterIntrinsic(IntrinsicInst &I) {
4326 assert(I.arg_size() == 2);
4327
4328 IRBuilder<> IRB(&I);
4329 Value *Shadow0 = getShadow(&I, 0);
4330 Value *Shadow1 = IRB.CreateOrReduce(getShadow(&I, 1));
4331 assert(Shadow0->getType() == Shadow1->getType());
4332 Value *S = IRB.CreateOr(Shadow0, Shadow1);
4333 assert(S->getType() == getShadowTy(&I));
4334 setShadow(&I, S);
4335 setOriginForNaryOp(I);
4336 }
4337
4338 // e.g., <4 x i32> @llvm.vector.partial.reduce.add (<4 x i32>, <8 x i32>)
4339 // acc addends
4340 // <4 x fp16> @llvm.vector.partial.reduce.fadd(<4 x fp16>, <8 x fp16>)
4341 // acc addends
4342 //
4343 // output[i] = acc[i] + addend[i] + addend[i+4]
4344 //
4345 // We approximate this as "all-or-nothing" for each element of the vector
4346 // i.e., even a single uninitialized bit in acc[i], addend[i], or
4347 // addend[i+4] will make output[i] fully uninitialized.
4348 //
4349 // By converting each vector element to a single value (0 or 1) representing
4350 // whether it is uninitialized, we can apply vector.partial.reduce.add to
4351 // compute the output shadow.
4352 //
4353 // N.B. this function is ready for scalable vectors, but its dependencies
4354 // are not.
4355 void handleVectorPartialReduceAddIntrinsic(IntrinsicInst &I) {
4356 IRBuilder<> IRB(&I);
4357
4358 assert(I.arg_size() == 2);
4359 [[maybe_unused]] Value *Accumulator = I.getArgOperand(0);
4360 [[maybe_unused]] Value *Addends = I.getArgOperand(1);
4361 assert(isa<VectorType>(Accumulator->getType()));
4362 assert(isa<VectorType>(Addends->getType()));
4363
4364 assert(I.getType() == Accumulator->getType());
4365
4366 assert(cast<VectorType>(Addends->getType())->getElementType() ==
4367 cast<VectorType>(I.getType())->getElementType());
4368 assert(cast<VectorType>(Addends->getType())
4369 ->getElementCount()
4370 .isKnownMultipleOf(
4371 cast<VectorType>(I.getType())->getElementCount()));
4372
4373 // e.g., <4 x i32>, <8 x i32>
4374 Value *SAcc = getShadow(&I, 0);
4375 Value *SAdd = getShadow(&I, 1);
4376
4377 // All-or-nothing shadows
4378 // e.g., <4 x i1>, <8 x i1>
4379 SAcc = IRB.CreateICmpNE(SAcc, getCleanShadow(SAcc));
4380 SAdd = IRB.CreateICmpNE(SAdd, getCleanShadow(SAdd));
4381
4382 // If we applied vector.partial.reduce.add to (<M x i1>, <N x i1>) shadows,
4383 // the sums might wrap around. Zero-extend to avoid this.
4384 // 16-bit for each sum (up to 65535) ought to be enough for anybody.
4385 SAcc = IRB.CreateZExt(
4386 SAcc,
4387 VectorType::get(IRB.getInt16Ty(),
4388 cast<VectorType>(SAcc->getType())->getElementCount()));
4389 SAdd = IRB.CreateZExt(
4390 SAdd,
4391 VectorType::get(IRB.getInt16Ty(),
4392 cast<VectorType>(SAdd->getType())->getElementCount()));
4393
4394 Value *SOutput = IRB.CreateIntrinsic(
4395 SAcc->getType(), Intrinsic::vector_partial_reduce_add, {SAcc, SAdd});
4396
4397 SOutput = IRB.CreateSExt(IRB.CreateICmpNE(SOutput, getCleanShadow(SOutput)),
4398 getShadowTy(&I));
4399
4400 setShadow(&I, SOutput);
4401 setOriginForNaryOp(I);
4402 }
4403
4404 // Instrument vector.reduce.or intrinsic.
4405 // Valid (non-poisoned) set bits in the operand pull low the
4406 // corresponding shadow bits.
4407 void handleVectorReduceOrIntrinsic(IntrinsicInst &I) {
4408 assert(I.arg_size() == 1);
4409
4410 IRBuilder<> IRB(&I);
4411 Value *OperandShadow = getShadow(&I, 0);
4412 Value *OperandUnsetBits = IRB.CreateNot(I.getOperand(0));
4413 Value *OperandUnsetOrPoison = IRB.CreateOr(OperandUnsetBits, OperandShadow);
4414 // Bit N is clean if any field's bit N is 1 and unpoison
4415 Value *OutShadowMask = IRB.CreateAndReduce(OperandUnsetOrPoison);
4416 // Otherwise, it is clean if every field's bit N is unpoison
4417 Value *OrShadow = IRB.CreateOrReduce(OperandShadow);
4418 Value *S = IRB.CreateAnd(OutShadowMask, OrShadow);
4419
4420 setShadow(&I, S);
4421 setOrigin(&I, getOrigin(&I, 0));
4422 }
4423
4424 // Instrument vector.reduce.and intrinsic.
4425 // Valid (non-poisoned) unset bits in the operand pull down the
4426 // corresponding shadow bits.
4427 void handleVectorReduceAndIntrinsic(IntrinsicInst &I) {
4428 assert(I.arg_size() == 1);
4429
4430 IRBuilder<> IRB(&I);
4431 Value *OperandShadow = getShadow(&I, 0);
4432 Value *OperandSetOrPoison = IRB.CreateOr(I.getOperand(0), OperandShadow);
4433 // Bit N is clean if any field's bit N is 0 and unpoison
4434 Value *OutShadowMask = IRB.CreateAndReduce(OperandSetOrPoison);
4435 // Otherwise, it is clean if every field's bit N is unpoison
4436 Value *OrShadow = IRB.CreateOrReduce(OperandShadow);
4437 Value *S = IRB.CreateAnd(OutShadowMask, OrShadow);
4438
4439 setShadow(&I, S);
4440 setOrigin(&I, getOrigin(&I, 0));
4441 }
4442
4443 void handleStmxcsr(IntrinsicInst &I) {
4444 IRBuilder<> IRB(&I);
4445 Value *Addr = I.getArgOperand(0);
4446 Type *Ty = IRB.getInt32Ty();
4447 Value *ShadowPtr =
4448 getShadowOriginPtr(Addr, IRB, Ty, Align(1), /*isStore*/ true).first;
4449
4450 IRB.CreateStore(getCleanShadow(Ty), ShadowPtr);
4451
4452 if (Opts.msan_check_access_address)
4453 insertCheckShadowOf(Addr, &I);
4454 }
4455
4456 void handleLdmxcsr(IntrinsicInst &I) {
4457 if (!InsertChecks)
4458 return;
4459
4460 IRBuilder<> IRB(&I);
4461 Value *Addr = I.getArgOperand(0);
4462 Type *Ty = IRB.getInt32Ty();
4463 const Align Alignment = Align(1);
4464 Value *ShadowPtr, *OriginPtr;
4465 std::tie(ShadowPtr, OriginPtr) =
4466 getShadowOriginPtr(Addr, IRB, Ty, Alignment, /*isStore*/ false);
4467
4468 if (Opts.msan_check_access_address)
4469 insertCheckShadowOf(Addr, &I);
4470
4471 Value *Shadow = IRB.CreateAlignedLoad(Ty, ShadowPtr, Alignment, "_ldmxcsr");
4472 Value *Origin = MS.TrackOrigins ? IRB.CreateLoad(MS.OriginTy, OriginPtr)
4473 : getCleanOrigin();
4474 insertCheckShadow(Shadow, Origin, &I);
4475 }
4476
4477 void handleMaskedExpandLoad(IntrinsicInst &I) {
4478 IRBuilder<> IRB(&I);
4479 Value *Ptr = I.getArgOperand(0);
4480 MaybeAlign Align = I.getParamAlign(0);
4481 Value *Mask = I.getArgOperand(1);
4482 Value *PassThru = I.getArgOperand(2);
4483
4484 if (Opts.msan_check_access_address) {
4485 insertCheckShadowOf(Ptr, &I);
4486 insertCheckShadowOf(Mask, &I);
4487 }
4488
4489 if (!PropagateShadow) {
4490 setShadow(&I, getCleanShadow(&I));
4491 setOrigin(&I, getCleanOrigin());
4492 return;
4493 }
4494
4495 Type *ShadowTy = getShadowTy(&I);
4496 Type *ElementShadowTy = cast<VectorType>(ShadowTy)->getElementType();
4497 auto [ShadowPtr, OriginPtr] =
4498 getShadowOriginPtr(Ptr, IRB, ElementShadowTy, Align, /*isStore*/ false);
4499
4500 Value *Shadow =
4501 IRB.CreateMaskedExpandLoad(ShadowTy, ShadowPtr, Align, Mask,
4502 getShadow(PassThru), "_msmaskedexpload");
4503
4504 setShadow(&I, Shadow);
4505
4506 // TODO: Store origins.
4507 setOrigin(&I, getCleanOrigin());
4508 }
4509
4510 void handleMaskedCompressStore(IntrinsicInst &I) {
4511 IRBuilder<> IRB(&I);
4512 Value *Values = I.getArgOperand(0);
4513 Value *Ptr = I.getArgOperand(1);
4514 MaybeAlign Align = I.getParamAlign(1);
4515 Value *Mask = I.getArgOperand(2);
4516
4517 if (Opts.msan_check_access_address) {
4518 insertCheckShadowOf(Ptr, &I);
4519 insertCheckShadowOf(Mask, &I);
4520 }
4521
4522 Value *Shadow = getShadow(Values);
4523 Type *ElementShadowTy =
4524 getShadowTy(cast<VectorType>(Values->getType())->getElementType());
4525 auto [ShadowPtr, OriginPtrs] =
4526 getShadowOriginPtr(Ptr, IRB, ElementShadowTy, Align, /*isStore*/ true);
4527
4528 IRB.CreateMaskedCompressStore(Shadow, ShadowPtr, Align, Mask);
4529
4530 // TODO: Store origins.
4531 }
4532
4533 void handleMaskedGather(IntrinsicInst &I) {
4534 IRBuilder<> IRB(&I);
4535 Value *Ptrs = I.getArgOperand(0);
4536 const Align Alignment = I.getParamAlign(0).valueOrOne();
4537 Value *Mask = I.getArgOperand(1);
4538 Value *PassThru = I.getArgOperand(2);
4539
4540 Type *PtrsShadowTy = getShadowTy(Ptrs);
4541 if (Opts.msan_check_access_address) {
4542 insertCheckShadowOf(Mask, &I);
4543 Value *MaskedPtrShadow = IRB.CreateSelect(
4544 Mask, getShadow(Ptrs), Constant::getNullValue((PtrsShadowTy)),
4545 "_msmaskedptrs");
4546 insertCheckShadow(MaskedPtrShadow, getOrigin(Ptrs), &I);
4547 }
4548
4549 if (!PropagateShadow) {
4550 setShadow(&I, getCleanShadow(&I));
4551 setOrigin(&I, getCleanOrigin());
4552 return;
4553 }
4554
4555 Type *ShadowTy = getShadowTy(&I);
4556 Type *ElementShadowTy = cast<VectorType>(ShadowTy)->getElementType();
4557 auto [ShadowPtrs, OriginPtrs] = getShadowOriginPtr(
4558 Ptrs, IRB, ElementShadowTy, Alignment, /*isStore*/ false);
4559
4560 Value *Shadow =
4561 IRB.CreateMaskedGather(ShadowTy, ShadowPtrs, Alignment, Mask,
4562 getShadow(PassThru), "_msmaskedgather");
4563
4564 setShadow(&I, Shadow);
4565
4566 // TODO: Store origins.
4567 setOrigin(&I, getCleanOrigin());
4568 }
4569
4570 void handleMaskedScatter(IntrinsicInst &I) {
4571 IRBuilder<> IRB(&I);
4572 Value *Values = I.getArgOperand(0);
4573 Value *Ptrs = I.getArgOperand(1);
4574 const Align Alignment = I.getParamAlign(1).valueOrOne();
4575 Value *Mask = I.getArgOperand(2);
4576
4577 Type *PtrsShadowTy = getShadowTy(Ptrs);
4578 if (Opts.msan_check_access_address) {
4579 insertCheckShadowOf(Mask, &I);
4580 Value *MaskedPtrShadow = IRB.CreateSelect(
4581 Mask, getShadow(Ptrs), Constant::getNullValue((PtrsShadowTy)),
4582 "_msmaskedptrs");
4583 insertCheckShadow(MaskedPtrShadow, getOrigin(Ptrs), &I);
4584 }
4585
4586 Value *Shadow = getShadow(Values);
4587 Type *ElementShadowTy =
4588 getShadowTy(cast<VectorType>(Values->getType())->getElementType());
4589 auto [ShadowPtrs, OriginPtrs] = getShadowOriginPtr(
4590 Ptrs, IRB, ElementShadowTy, Alignment, /*isStore*/ true);
4591
4592 IRB.CreateMaskedScatter(Shadow, ShadowPtrs, Alignment, Mask);
4593
4594 // TODO: Store origin.
4595 }
4596
4597 // Intrinsic::masked_store
4598 //
4599 // Note: handleAVXMaskedStore handles AVX/AVX2 variants, though AVX512 masked
4600 // stores are lowered to Intrinsic::masked_store.
4601 void handleMaskedStore(IntrinsicInst &I) {
4602 IRBuilder<> IRB(&I);
4603 Value *V = I.getArgOperand(0);
4604 Value *Ptr = I.getArgOperand(1);
4605 const Align Alignment = I.getParamAlign(1).valueOrOne();
4606 Value *Mask = I.getArgOperand(2);
4607 Value *Shadow = getShadow(V);
4608
4609 if (Opts.msan_check_access_address) {
4610 insertCheckShadowOf(Ptr, &I);
4611 insertCheckShadowOf(Mask, &I);
4612 }
4613
4614 Value *ShadowPtr;
4615 Value *OriginPtr;
4616 std::tie(ShadowPtr, OriginPtr) = getShadowOriginPtr(
4617 Ptr, IRB, Shadow->getType(), Alignment, /*isStore*/ true);
4618
4619 IRB.CreateMaskedStore(Shadow, ShadowPtr, Alignment, Mask);
4620
4621 if (!MS.TrackOrigins)
4622 return;
4623
4624 // TODO: Only update origins for active lanes with non-zero shadow;
4625 // masked-off lanes may be unmapped/out-of-bounds or hold distinct
4626 // origins (including when the mask is all zero).
4627 auto &DL = F.getDataLayout();
4628 paintOrigin(IRB, getOrigin(V), OriginPtr,
4629 DL.getTypeStoreSize(Shadow->getType()),
4630 std::max(Alignment, kMinOriginAlignment));
4631 }
4632
4633 // Intrinsic::masked_load
4634 //
4635 // Note: handleAVXMaskedLoad handles AVX/AVX2 variants, though AVX512 masked
4636 // loads are lowered to Intrinsic::masked_load.
4637 void handleMaskedLoad(IntrinsicInst &I) {
4638 IRBuilder<> IRB(&I);
4639 Value *Ptr = I.getArgOperand(0);
4640 const Align Alignment = I.getParamAlign(0).valueOrOne();
4641 Value *Mask = I.getArgOperand(1);
4642 Value *PassThru = I.getArgOperand(2);
4643
4644 if (Opts.msan_check_access_address) {
4645 insertCheckShadowOf(Ptr, &I);
4646 insertCheckShadowOf(Mask, &I);
4647 }
4648
4649 if (!PropagateShadow) {
4650 setShadow(&I, getCleanShadow(&I));
4651 setOrigin(&I, getCleanOrigin());
4652 return;
4653 }
4654
4655 Type *ShadowTy = getShadowTy(&I);
4656 Value *ShadowPtr, *OriginPtr;
4657 std::tie(ShadowPtr, OriginPtr) =
4658 getShadowOriginPtr(Ptr, IRB, ShadowTy, Alignment, /*isStore*/ false);
4659 setShadow(&I, IRB.CreateMaskedLoad(ShadowTy, ShadowPtr, Alignment, Mask,
4660 getShadow(PassThru), "_msmaskedld"));
4661
4662 if (!MS.TrackOrigins)
4663 return;
4664
4665 // Choose between PassThru's and the loaded value's origins.
4666 Value *MaskedPassThruShadow = IRB.CreateAnd(
4667 getShadow(PassThru), IRB.CreateSExt(IRB.CreateNeg(Mask), ShadowTy));
4668
4669 Value *NotNull = convertToBool(MaskedPassThruShadow, IRB, "_mscmp");
4670
4671 Value *PtrOrigin = IRB.CreateLoad(MS.OriginTy, OriginPtr);
4672 Value *Origin = IRB.CreateSelect(NotNull, getOrigin(PassThru), PtrOrigin);
4673
4674 setOrigin(&I, Origin);
4675 }
4676
4677 // e.g., <4 x i32> @llvm.masked.udiv.v4i32(<4 x i32> %dividend,
4678 // <4 x i32> %divisor,
4679 // <4 x i1> %mask)
4680 //
4681 // As handleIntegerDiv(), but per-lane: strict on the divisor and propagating
4682 // the dividend, both only on the enabled lanes. Disabled lanes cannot cause
4683 // undefined behaviour, and their result is poison.
4684 void handleMaskedIntegerDivRem(IntrinsicInst &I) {
4685 assert(I.arg_size() == 3);
4686 IRBuilder<> IRB(&I);
4687 Value *Dividend = I.getArgOperand(0);
4688 Value *Divisor = I.getArgOperand(1);
4689 Value *Mask = I.getArgOperand(2);
4690
4691 insertCheckShadowOf(Mask, &I);
4692
4693 Value *MaskedDivisorShadow = IRB.CreateSelect(
4694 Mask, getShadow(Divisor), getCleanShadow(Divisor), "_msmaskeddivisor");
4695 insertCheckShadow(MaskedDivisorShadow, getOrigin(Divisor), &I);
4696
4697 if (!PropagateShadow) {
4698 setShadow(&I, getCleanShadow(&I));
4699 setOrigin(&I, getCleanOrigin());
4700 return;
4701 }
4702
4703 setShadow(&I, IRB.CreateSelect(Mask, getShadow(Dividend),
4704 getPoisonedShadow(&I), "_msmaskeddiv"));
4705 setOrigin(&I, getOrigin(Dividend));
4706 }
4707
4708 // e.g., i32 @llvm.experimental.vector.extract.last.active.v4i32(
4709 // <4 x i32> %data, <4 x i1> %mask, i32 %passthru)
4710 void handleVectorExtractLastActive(IntrinsicInst &I) {
4711 assert(I.arg_size() == 3);
4712 IRBuilder<> IRB(&I);
4713 Value *Data = I.getArgOperand(0);
4714 Value *Mask = I.getArgOperand(1);
4715 Value *PassThru = I.getArgOperand(2);
4716
4717 assert(isa<VectorType>(Data->getType()));
4718 assert(isa<VectorType>(Mask->getType()));
4719 assert(!isa<VectorType>(PassThru->getType()));
4720 assert(!isa<VectorType>(I.getType()));
4721 assert(I.getType() == PassThru->getType());
4722 assert(cast<VectorType>(Data->getType())->getElementType() == I.getType());
4723 assert(cast<VectorType>(Mask->getType())->getElementType() ==
4724 IRB.getInt1Ty());
4725 assert(cast<VectorType>(Data->getType())->getElementCount() ==
4726 cast<VectorType>(Mask->getType())->getElementCount());
4727
4728 insertCheckShadowOf(Mask, &I);
4729
4730 if (!PropagateShadow) {
4731 setShadow(&I, getCleanShadow(&I));
4732 setOrigin(&I, getCleanOrigin());
4733 return;
4734 }
4735
4736 Value *DataShadow = getShadow(Data);
4737 Value *Shadow = IRB.CreateIntrinsic(
4738 Intrinsic::experimental_vector_extract_last_active,
4739 {DataShadow->getType()}, {DataShadow, Mask, getShadow(PassThru)},
4740 /*FMFSource=*/{}, "_msprop_vector_extract_last_active");
4741 setShadow(&I, Shadow);
4742
4743 if (MS.TrackOrigins) {
4744 Value *AnyActive = IRB.CreateOrReduce(Mask);
4745 setOrigin(&I, IRB.CreateSelect(AnyActive, getOrigin(Data),
4746 getOrigin(PassThru)));
4747 }
4748 }
4749
4750 // e.g., void @llvm.x86.avx.maskstore.ps.256(ptr, <8 x i32>, <8 x float>)
4751 // dst mask src
4752 //
4753 // AVX512 masked stores are lowered to Intrinsic::masked_load and are handled
4754 // by handleMaskedStore.
4755 //
4756 // This function handles AVX and AVX2 masked stores; these use the MSBs of a
4757 // vector of integers, unlike the LLVM masked intrinsics, which require a
4758 // vector of booleans. X86InstCombineIntrinsic.cpp::simplifyX86MaskedLoad
4759 // mentions that the x86 backend does not know how to efficiently convert
4760 // from a vector of booleans back into the AVX mask format; therefore, they
4761 // (and we) do not reduce AVX/AVX2 masked intrinsics into LLVM masked
4762 // intrinsics.
4763 void handleAVXMaskedStore(IntrinsicInst &I) {
4764 assert(I.arg_size() == 3);
4765
4766 IRBuilder<> IRB(&I);
4767
4768 Value *Dst = I.getArgOperand(0);
4769 assert(Dst->getType()->isPointerTy() && "Destination is not a pointer!");
4770
4771 Value *Mask = I.getArgOperand(1);
4772 assert(isa<VectorType>(Mask->getType()) && "Mask is not a vector!");
4773
4774 Value *Src = I.getArgOperand(2);
4775 assert(isa<VectorType>(Src->getType()) && "Source is not a vector!");
4776
4777 const Align Alignment = Align(1);
4778
4779 Value *SrcShadow = getShadow(Src);
4780
4781 if (Opts.msan_check_access_address) {
4782 insertCheckShadowOf(Dst, &I);
4783 insertCheckShadowOf(Mask, &I);
4784 }
4785
4786 Value *DstShadowPtr;
4787 Value *DstOriginPtr;
4788 std::tie(DstShadowPtr, DstOriginPtr) = getShadowOriginPtr(
4789 Dst, IRB, SrcShadow->getType(), Alignment, /*isStore*/ true);
4790
4791 SmallVector<Value *, 2> ShadowArgs;
4792 ShadowArgs.append(1, DstShadowPtr);
4793 ShadowArgs.append(1, Mask);
4794 // The intrinsic may require floating-point but shadows can be arbitrary
4795 // bit patterns, of which some would be interpreted as "invalid"
4796 // floating-point values (NaN etc.); we assume the intrinsic will happily
4797 // copy them.
4798 ShadowArgs.append(1, IRB.CreateBitCast(SrcShadow, Src->getType()));
4799
4800 CallInst *CI = IRB.CreateIntrinsicWithoutFolding(
4801 IRB.getVoidTy(), I.getIntrinsicID(), ShadowArgs);
4802 setShadow(&I, CI);
4803
4804 if (!MS.TrackOrigins)
4805 return;
4806
4807 // Approximation only
4808 auto &DL = F.getDataLayout();
4809 paintOrigin(IRB, getOrigin(Src), DstOriginPtr,
4810 DL.getTypeStoreSize(SrcShadow->getType()),
4811 std::max(Alignment, kMinOriginAlignment));
4812 }
4813
4814 // e.g., <8 x float> @llvm.x86.avx.maskload.ps.256(ptr, <8 x i32>)
4815 // return src mask
4816 //
4817 // Masked-off values are replaced with 0, which conveniently also represents
4818 // initialized memory.
4819 //
4820 // AVX512 masked stores are lowered to Intrinsic::masked_load and are handled
4821 // by handleMaskedStore.
4822 //
4823 // We do not combine this with handleMaskedLoad; see comment in
4824 // handleAVXMaskedStore for the rationale.
4825 //
4826 // This is subtly different than handleIntrinsicByApplyingToShadow(I, 1)
4827 // because we need to apply getShadowOriginPtr, not getShadow, to the first
4828 // parameter.
4829 void handleAVXMaskedLoad(IntrinsicInst &I) {
4830 assert(I.arg_size() == 2);
4831
4832 IRBuilder<> IRB(&I);
4833
4834 Value *Src = I.getArgOperand(0);
4835 assert(Src->getType()->isPointerTy() && "Source is not a pointer!");
4836
4837 Value *Mask = I.getArgOperand(1);
4838 assert(isa<VectorType>(Mask->getType()) && "Mask is not a vector!");
4839
4840 const Align Alignment = Align(1);
4841
4842 if (Opts.msan_check_access_address) {
4843 insertCheckShadowOf(Mask, &I);
4844 }
4845
4846 Type *SrcShadowTy = getShadowTy(Src);
4847 Value *SrcShadowPtr, *SrcOriginPtr;
4848 std::tie(SrcShadowPtr, SrcOriginPtr) =
4849 getShadowOriginPtr(Src, IRB, SrcShadowTy, Alignment, /*isStore*/ false);
4850
4851 SmallVector<Value *, 2> ShadowArgs;
4852 ShadowArgs.append(1, SrcShadowPtr);
4853 ShadowArgs.append(1, Mask);
4854
4855 CallInst *CI = IRB.CreateIntrinsicWithoutFolding(
4856 I.getType(), I.getIntrinsicID(), ShadowArgs);
4857 // The AVX masked load intrinsics do not have integer variants. We use the
4858 // floating-point variants, which will happily copy the shadows even if
4859 // they are interpreted as "invalid" floating-point values (NaN etc.).
4860 setShadow(&I, IRB.CreateBitCast(CI, getShadowTy(&I)));
4861
4862 if (!MS.TrackOrigins)
4863 return;
4864
4865 // The "pass-through" value is always zero (initialized). To the extent
4866 // that that results in initialized aligned 4-byte chunks, the origin value
4867 // is ignored. It is therefore correct to simply copy the origin from src.
4868 Value *PtrSrcOrigin = IRB.CreateLoad(MS.OriginTy, SrcOriginPtr);
4869 setOrigin(&I, PtrSrcOrigin);
4870 }
4871
4872 // Test whether the mask indices are initialized, only checking the bits that
4873 // are actually used.
4874 //
4875 // e.g., if Idx is <32 x i16>, only (log2(32) == 5) bits of each index are
4876 // used/checked.
4877 void maskedCheckAVXIndexShadow(IRBuilder<> &IRB, Value *Idx, Instruction *I) {
4878 assert(isFixedIntVector(Idx));
4879 auto IdxVectorSize =
4880 cast<FixedVectorType>(Idx->getType())->getNumElements();
4881 assert(isPowerOf2_64(IdxVectorSize));
4882
4883 // Compiler isn't smart enough, let's help it
4884 if (isa<Constant>(Idx))
4885 return;
4886
4887 auto *IdxShadow = getShadow(Idx);
4888 Value *Truncated = IRB.CreateTrunc(
4889 IdxShadow,
4890 FixedVectorType::get(Type::getIntNTy(*MS.C, Log2_64(IdxVectorSize)),
4891 IdxVectorSize));
4892 insertCheckShadow(Truncated, getOrigin(Idx), I);
4893 }
4894
4895 // Instrument AVX permutation intrinsic.
4896 // We apply the same permutation (argument index 1) to the shadow.
4897 void handleAVXVpermilvar(IntrinsicInst &I) {
4898 IRBuilder<> IRB(&I);
4899 Value *Shadow = getShadow(&I, 0);
4900 maskedCheckAVXIndexShadow(IRB, I.getArgOperand(1), &I);
4901
4902 // Shadows are integer-ish types but some intrinsics require a
4903 // different (e.g., floating-point) type.
4904 Shadow = IRB.CreateBitCast(Shadow, I.getArgOperand(0)->getType());
4905 CallInst *CI = IRB.CreateIntrinsicWithoutFolding(
4906 I.getType(), I.getIntrinsicID(), {Shadow, I.getArgOperand(1)});
4907
4908 setShadow(&I, IRB.CreateBitCast(CI, getShadowTy(&I)));
4909 setOriginForNaryOp(I);
4910 }
4911
4912 // Instrument AVX permutation intrinsic.
4913 // We apply the same permutation (argument index 1) to the shadows.
4914 void handleAVXVpermi2var(IntrinsicInst &I) {
4915 assert(I.arg_size() == 3);
4916 assert(isa<FixedVectorType>(I.getArgOperand(0)->getType()));
4917 assert(isa<FixedVectorType>(I.getArgOperand(1)->getType()));
4918 assert(isa<FixedVectorType>(I.getArgOperand(2)->getType()));
4919 [[maybe_unused]] auto ArgVectorSize =
4920 cast<FixedVectorType>(I.getArgOperand(0)->getType())->getNumElements();
4921 assert(cast<FixedVectorType>(I.getArgOperand(1)->getType())
4922 ->getNumElements() == ArgVectorSize);
4923 assert(cast<FixedVectorType>(I.getArgOperand(2)->getType())
4924 ->getNumElements() == ArgVectorSize);
4925 assert(I.getArgOperand(0)->getType() == I.getArgOperand(2)->getType());
4926 assert(I.getType() == I.getArgOperand(0)->getType());
4927 assert(I.getArgOperand(1)->getType()->isIntOrIntVectorTy());
4928 IRBuilder<> IRB(&I);
4929 Value *AShadow = getShadow(&I, 0);
4930 Value *Idx = I.getArgOperand(1);
4931 Value *BShadow = getShadow(&I, 2);
4932
4933 maskedCheckAVXIndexShadow(IRB, Idx, &I);
4934
4935 // Shadows are integer-ish types but some intrinsics require a
4936 // different (e.g., floating-point) type.
4937 AShadow = IRB.CreateBitCast(AShadow, I.getArgOperand(0)->getType());
4938 BShadow = IRB.CreateBitCast(BShadow, I.getArgOperand(2)->getType());
4939 CallInst *CI = IRB.CreateIntrinsicWithoutFolding(
4940 I.getType(), I.getIntrinsicID(), {AShadow, Idx, BShadow});
4941 setShadow(&I, IRB.CreateBitCast(CI, getShadowTy(&I)));
4942 setOriginForNaryOp(I);
4943 }
4944
4945 [[maybe_unused]] static bool isFixedIntVectorTy(const Type *T) {
4946 return isa<FixedVectorType>(T) && T->isIntOrIntVectorTy();
4947 }
4948
4949 [[maybe_unused]] static bool isFixedFPVectorTy(const Type *T) {
4950 return isa<FixedVectorType>(T) && T->isFPOrFPVectorTy();
4951 }
4952
4953 [[maybe_unused]] static bool isFixedIntVector(const Value *V) {
4954 return isFixedIntVectorTy(V->getType());
4955 }
4956
4957 [[maybe_unused]] static bool isFixedFPVector(const Value *V) {
4958 return isFixedFPVectorTy(V->getType());
4959 }
4960
4961 // e.g., <16 x i32> @llvm.x86.avx512.mask.cvtps2dq.512
4962 // (<16 x float> a, <16 x i32> writethru, i16 mask,
4963 // i32 rounding)
4964 //
4965 // Inconveniently, some similar intrinsics have a different operand order:
4966 // <16 x i16> @llvm.x86.avx512.mask.vcvtps2ph.512
4967 // (<16 x float> a, i32 rounding, <16 x i16> writethru,
4968 // i16 mask)
4969 //
4970 // If the return type has more elements than A, the excess elements are
4971 // zeroed (and the corresponding shadow is initialized).
4972 // <8 x i16> @llvm.x86.avx512.mask.vcvtps2ph.128
4973 // (<4 x float> a, i32 rounding, <8 x i16> writethru,
4974 // i8 mask)
4975 //
4976 // dst[i] = mask[i] ? convert(a[i]) : writethru[i]
4977 // dst_shadow[i] = mask[i] ? all_or_nothing(a_shadow[i]) : writethru_shadow[i]
4978 // where all_or_nothing(x) is fully uninitialized if x has any
4979 // uninitialized bits
4980 void handleAVX512VectorConvertFPToInt(IntrinsicInst &I, bool LastMask) {
4981 IRBuilder<> IRB(&I);
4982
4983 assert(I.arg_size() == 4);
4984 Value *A = I.getOperand(0);
4985 Value *WriteThrough;
4986 Value *Mask;
4988 if (LastMask) {
4989 WriteThrough = I.getOperand(2);
4990 Mask = I.getOperand(3);
4991 RoundingMode = I.getOperand(1);
4992 } else {
4993 WriteThrough = I.getOperand(1);
4994 Mask = I.getOperand(2);
4995 RoundingMode = I.getOperand(3);
4996 }
4997
4998 assert(isFixedFPVector(A));
4999 assert(isFixedIntVector(WriteThrough));
5000
5001 unsigned ANumElements =
5002 cast<FixedVectorType>(A->getType())->getNumElements();
5003 [[maybe_unused]] unsigned WriteThruNumElements =
5004 cast<FixedVectorType>(WriteThrough->getType())->getNumElements();
5005 assert(ANumElements == WriteThruNumElements ||
5006 ANumElements * 2 == WriteThruNumElements);
5007
5008 assert(Mask->getType()->isIntegerTy());
5009 unsigned MaskNumElements = Mask->getType()->getScalarSizeInBits();
5010 assert(ANumElements == MaskNumElements ||
5011 ANumElements * 2 == MaskNumElements);
5012
5013 assert(WriteThruNumElements == MaskNumElements);
5014
5015 // Some bits of the mask may be unused, though it's unusual to have partly
5016 // uninitialized bits.
5017 insertCheckShadowOf(Mask, &I);
5018
5019 assert(RoundingMode->getType()->isIntegerTy());
5020 // Only some bits of the rounding mode are used, though it's very
5021 // unusual to have uninitialized bits there (more commonly, it's a
5022 // constant).
5023 insertCheckShadowOf(RoundingMode, &I);
5024
5025 assert(I.getType() == WriteThrough->getType());
5026
5027 Value *AShadow = getShadow(A);
5028 AShadow = maybeExtendVectorShadowWithZeros(AShadow, I);
5029
5030 if (ANumElements * 2 == MaskNumElements) {
5031 // Ensure that the irrelevant bits of the mask are zero, hence selecting
5032 // from the zeroed shadow instead of the writethrough's shadow.
5033 Mask =
5034 IRB.CreateTrunc(Mask, IRB.getIntNTy(ANumElements), "_ms_mask_trunc");
5035 Mask =
5036 IRB.CreateZExt(Mask, IRB.getIntNTy(MaskNumElements), "_ms_mask_zext");
5037 }
5038
5039 // Convert i16 mask to <16 x i1>
5040 Mask = IRB.CreateBitCast(
5041 Mask, FixedVectorType::get(IRB.getInt1Ty(), MaskNumElements),
5042 "_ms_mask_bitcast");
5043
5044 /// For floating-point to integer conversion, the output is:
5045 /// - fully uninitialized if *any* bit of the input is uninitialized
5046 /// - fully ininitialized if all bits of the input are ininitialized
5047 /// We apply the same principle on a per-element basis for vectors.
5048 ///
5049 /// We use the scalar width of the return type instead of A's.
5050 AShadow = IRB.CreateSExt(
5051 IRB.CreateICmpNE(AShadow, getCleanShadow(AShadow->getType())),
5052 getShadowTy(&I), "_ms_a_shadow");
5053
5054 Value *WriteThroughShadow = getShadow(WriteThrough);
5055 Value *Shadow = IRB.CreateSelect(Mask, AShadow, WriteThroughShadow,
5056 "_ms_writethru_select");
5057
5058 setShadow(&I, Shadow);
5059 setOriginForNaryOp(I);
5060 }
5061
5062 static SmallVector<int, 8> getPclmulMask(unsigned Width, bool OddElements) {
5063 SmallVector<int, 8> Mask;
5064 for (unsigned X = OddElements ? 1 : 0; X < Width; X += 2) {
5065 Mask.append(2, X);
5066 }
5067 return Mask;
5068 }
5069
5070 // Instrument pclmul intrinsics.
5071 // These intrinsics operate either on odd or on even elements of the input
5072 // vectors, depending on the constant in the 3rd argument, ignoring the rest.
5073 // Replace the unused elements with copies of the used ones, ex:
5074 // (0, 1, 2, 3) -> (0, 0, 2, 2) (even case)
5075 // or
5076 // (0, 1, 2, 3) -> (1, 1, 3, 3) (odd case)
5077 // and then apply the usual shadow combining logic.
5078 void handlePclmulIntrinsic(IntrinsicInst &I) {
5079 IRBuilder<> IRB(&I);
5080 unsigned Width =
5081 cast<FixedVectorType>(I.getArgOperand(0)->getType())->getNumElements();
5082 assert(isa<ConstantInt>(I.getArgOperand(2)) &&
5083 "pclmul 3rd operand must be a constant");
5084 unsigned Imm = cast<ConstantInt>(I.getArgOperand(2))->getZExtValue();
5085 Value *Shuf0 = IRB.CreateShuffleVector(getShadow(&I, 0),
5086 getPclmulMask(Width, Imm & 0x01));
5087 Value *Shuf1 = IRB.CreateShuffleVector(getShadow(&I, 1),
5088 getPclmulMask(Width, Imm & 0x10));
5089 ShadowAndOriginCombiner SOC(this, IRB);
5090 SOC.Add(Shuf0, getOrigin(&I, 0));
5091 SOC.Add(Shuf1, getOrigin(&I, 1));
5092 SOC.Done(&I);
5093 }
5094
5095 // Instrument _mm_*_sd|ss intrinsics
5096 void handleUnarySdSsIntrinsic(IntrinsicInst &I) {
5097 IRBuilder<> IRB(&I);
5098 unsigned Width =
5099 cast<FixedVectorType>(I.getArgOperand(0)->getType())->getNumElements();
5100 Value *First = getShadow(&I, 0);
5101 Value *Second = getShadow(&I, 1);
5102 // First element of second operand, remaining elements of first operand
5103 SmallVector<int, 16> Mask;
5104 Mask.push_back(Width);
5105 for (unsigned i = 1; i < Width; i++)
5106 Mask.push_back(i);
5107 Value *Shadow = IRB.CreateShuffleVector(First, Second, Mask);
5108
5109 setShadow(&I, Shadow);
5110 setOriginForNaryOp(I);
5111 }
5112
5113 void handleVtestIntrinsic(IntrinsicInst &I) {
5114 IRBuilder<> IRB(&I);
5115 Value *Shadow0 = getShadow(&I, 0);
5116 Value *Shadow1 = getShadow(&I, 1);
5117 Value *Or = IRB.CreateOr(Shadow0, Shadow1);
5118 Value *NZ = IRB.CreateICmpNE(Or, Constant::getNullValue(Or->getType()));
5119 Value *Scalar = convertShadowToScalar(NZ, IRB);
5120 Value *Shadow = IRB.CreateZExt(Scalar, getShadowTy(&I));
5121
5122 setShadow(&I, Shadow);
5123 setOriginForNaryOp(I);
5124 }
5125
5126 void handleBinarySdSsIntrinsic(IntrinsicInst &I) {
5127 IRBuilder<> IRB(&I);
5128 unsigned Width =
5129 cast<FixedVectorType>(I.getArgOperand(0)->getType())->getNumElements();
5130 Value *First = getShadow(&I, 0);
5131 Value *Second = getShadow(&I, 1);
5132 Value *OrShadow = IRB.CreateOr(First, Second);
5133 // First element of both OR'd together, remaining elements of first operand
5134 SmallVector<int, 16> Mask;
5135 Mask.push_back(Width);
5136 for (unsigned i = 1; i < Width; i++)
5137 Mask.push_back(i);
5138 Value *Shadow = IRB.CreateShuffleVector(First, OrShadow, Mask);
5139
5140 setShadow(&I, Shadow);
5141 setOriginForNaryOp(I);
5142 }
5143
5144 // _mm_round_ps / _mm_round_ps.
5145 // Similar to maybeHandleSimpleNomemIntrinsic except
5146 // the second argument is guaranteed to be a constant integer.
5147 void handleRoundPdPsIntrinsic(IntrinsicInst &I) {
5148 assert(I.getArgOperand(0)->getType() == I.getType());
5149 assert(I.arg_size() == 2);
5150 assert(isa<ConstantInt>(I.getArgOperand(1)));
5151
5152 IRBuilder<> IRB(&I);
5153 ShadowAndOriginCombiner SC(this, IRB);
5154 SC.Add(I.getArgOperand(0));
5155 SC.Done(&I);
5156 }
5157
5158 // Instrument @llvm.abs intrinsic.
5159 //
5160 // e.g., i32 @llvm.abs.i32 (i32 <Src>, i1 <is_int_min_poison>)
5161 // <4 x i32> @llvm.abs.v4i32(<4 x i32> <Src>, i1 <is_int_min_poison>)
5162 void handleAbsIntrinsic(IntrinsicInst &I) {
5163 assert(I.arg_size() == 2);
5164 Value *Src = I.getArgOperand(0);
5165 Value *IsIntMinPoison = I.getArgOperand(1);
5166
5167 assert(I.getType()->isIntOrIntVectorTy());
5168
5169 assert(Src->getType() == I.getType());
5170
5171 assert(IsIntMinPoison->getType()->isIntegerTy());
5172 assert(IsIntMinPoison->getType()->getIntegerBitWidth() == 1);
5173
5174 IRBuilder<> IRB(&I);
5175 Value *SrcShadow = getShadow(Src);
5176
5177 APInt MinVal =
5178 APInt::getSignedMinValue(Src->getType()->getScalarSizeInBits());
5179 Value *MinValVec = ConstantInt::get(Src->getType(), MinVal);
5180 Value *SrcIsMin = IRB.CreateICmp(CmpInst::ICMP_EQ, Src, MinValVec);
5181
5182 Value *PoisonedShadow = getPoisonedShadow(Src);
5183 Value *PoisonedIfIntMinShadow =
5184 IRB.CreateSelect(SrcIsMin, PoisonedShadow, SrcShadow);
5185 Value *Shadow =
5186 IRB.CreateSelect(IsIntMinPoison, PoisonedIfIntMinShadow, SrcShadow);
5187
5188 setShadow(&I, Shadow);
5189 setOrigin(&I, getOrigin(&I, 0));
5190 }
5191
5192 void handleIsFpClass(IntrinsicInst &I) {
5193 IRBuilder<> IRB(&I);
5194 Value *Shadow = getShadow(&I, 0);
5195 setShadow(&I, IRB.CreateICmpNE(Shadow, getCleanShadow(Shadow)));
5196 setOrigin(&I, getOrigin(&I, 0));
5197 }
5198
5199 void handleArithmeticWithOverflow(IntrinsicInst &I) {
5200 IRBuilder<> IRB(&I);
5201 Value *Shadow0 = getShadow(&I, 0);
5202 Value *Shadow1 = getShadow(&I, 1);
5203 Value *ShadowElt0 = IRB.CreateOr(Shadow0, Shadow1);
5204 Value *ShadowElt1 =
5205 IRB.CreateICmpNE(ShadowElt0, getCleanShadow(ShadowElt0));
5206
5207 Value *Shadow = PoisonValue::get(getShadowTy(&I));
5208 Shadow = IRB.CreateInsertValue(Shadow, ShadowElt0, 0);
5209 Shadow = IRB.CreateInsertValue(Shadow, ShadowElt1, 1);
5210
5211 setShadow(&I, Shadow);
5212 setOriginForNaryOp(I);
5213 }
5214
5215 void handleModfOrSincos(IntrinsicInst &I) {
5216 IRBuilder<> IRB(&I);
5217 Value *ArgShadow = getShadow(&I, 0);
5218 Value *Shadow = PoisonValue::get(getShadowTy(&I));
5219 Shadow = IRB.CreateInsertValue(Shadow, ArgShadow, 0);
5220 Shadow = IRB.CreateInsertValue(Shadow, ArgShadow, 1);
5221 setShadow(&I, Shadow);
5222 setOrigin(&I, getOrigin(&I, 0));
5223 }
5224
5225 Value *extractLowerShadow(IRBuilder<> &IRB, Value *V) {
5226 assert(isa<FixedVectorType>(V->getType()));
5227 assert(cast<FixedVectorType>(V->getType())->getNumElements() > 0);
5228 Value *Shadow = getShadow(V);
5229 return IRB.CreateExtractElement(Shadow,
5230 ConstantInt::get(IRB.getInt32Ty(), 0));
5231 }
5232
5233 // Handle llvm.x86.avx512.mask.pmov{,s,us}.*.{128,256,512}
5234 //
5235 // e.g., call <16 x i8> @llvm.x86.avx512.mask.pmov.qb.512
5236 // (<8 x i64>, <16 x i8>, i8)
5237 // A WriteThru Mask
5238 //
5239 // call <16 x i8> @llvm.x86.avx512.mask.pmovs.db.512
5240 // (<16 x i32>, <16 x i8>, i16)
5241 //
5242 // Dst[i] = Mask[i] ? truncate_or_saturate(A[i]) : WriteThru[i]
5243 // Dst_shadow[i] = Mask[i] ? truncate(A_shadow[i]) : WriteThru_shadow[i]
5244 //
5245 // If Dst has more elements than A, the excess elements are zeroed (and the
5246 // corresponding shadow is initialized).
5247 //
5248 // Note: for PMOV (truncation), handleIntrinsicByApplyingToShadow is precise
5249 // and is much faster than this handler.
5250 void handleAVX512VectorDownConvert(IntrinsicInst &I) {
5251 IRBuilder<> IRB(&I);
5252
5253 assert(I.arg_size() == 3);
5254 Value *A = I.getOperand(0);
5255 Value *WriteThrough = I.getOperand(1);
5256 Value *Mask = I.getOperand(2);
5257
5258 assert(isFixedIntVector(A));
5259 assert(isFixedIntVector(WriteThrough));
5260
5261 unsigned ANumElements =
5262 cast<FixedVectorType>(A->getType())->getNumElements();
5263 unsigned OutputNumElements =
5264 cast<FixedVectorType>(WriteThrough->getType())->getNumElements();
5265 assert(ANumElements == OutputNumElements ||
5266 ANumElements * 2 == OutputNumElements);
5267 // N.B. some PMOV{,S,US} instructions have a 4x or even 8x ratio in the
5268 // number of elements e.g.,
5269 // <16 x i8> @llvm.x86.avx512.mask.pmovs.qb.256
5270 // (<4 x i64>, <16 x i8>, i8)
5271 // <16 x i8> @llvm.x86.avx512.mask.pmovs.qb.128
5272 // (<2 x i64>, <16 x i8>, i8)
5273 // However, we currently handle those elsewhere.
5274
5275 assert(Mask->getType()->isIntegerTy());
5276 insertCheckShadowOf(Mask, &I);
5277
5278 // The mask has 1 bit per element of A, but a minimum of 8 bits.
5279 if (Mask->getType()->getScalarSizeInBits() == 8 && OutputNumElements < 8)
5280 Mask = IRB.CreateTrunc(Mask, Type::getIntNTy(*MS.C, OutputNumElements));
5281 assert(Mask->getType()->getScalarSizeInBits() == ANumElements);
5282
5283 assert(I.getType() == WriteThrough->getType());
5284
5285 // Widen the mask, if necessary, to have one bit per element of the output
5286 // vector.
5287 // We want the extra bits to have '1's, so that the CreateSelect will
5288 // select the values from AShadow instead of WriteThroughShadow ("maskless"
5289 // versions of the intrinsics are sometimes implemented using an all-1's
5290 // mask and an undefined value for WriteThroughShadow). We accomplish this
5291 // by using bitwise NOT before and after the ZExt.
5292 if (ANumElements != OutputNumElements) {
5293 Mask = IRB.CreateNot(Mask);
5294 Mask = IRB.CreateZExt(Mask, Type::getIntNTy(*MS.C, OutputNumElements),
5295 "_ms_widen_mask");
5296 Mask = IRB.CreateNot(Mask);
5297 }
5298 Mask = IRB.CreateBitCast(
5299 Mask, FixedVectorType::get(IRB.getInt1Ty(), OutputNumElements));
5300
5301 Value *AShadow = getShadow(A);
5302
5303 // The return type might have more elements than the input.
5304 // Temporarily shrink the return type's number of elements.
5305 VectorType *ShadowType = maybeShrinkVectorShadowType(A, I);
5306
5307 // PMOV truncates; PMOVS/PMOVUS uses signed/unsigned saturation.
5308 // This handler treats them all as truncation, which leads to some rare
5309 // false positives in the cases where the truncated bytes could
5310 // unambiguously saturate the value e.g., if A = ??????10 ????????
5311 // (big-endian), the unsigned saturated byte conversion is 11111111 i.e.,
5312 // fully defined, but the truncated byte is ????????.
5313 //
5314 // TODO: use GetMinMaxUnsigned() to handle saturation precisely.
5315 AShadow = IRB.CreateTrunc(AShadow, ShadowType, "_ms_trunc_shadow");
5316 AShadow = maybeExtendVectorShadowWithZeros(AShadow, I);
5317
5318 Value *WriteThroughShadow = getShadow(WriteThrough);
5319
5320 Value *Shadow = IRB.CreateSelect(Mask, AShadow, WriteThroughShadow);
5321 setShadow(&I, Shadow);
5322 setOriginForNaryOp(I);
5323 }
5324
5325 // Handle llvm.x86.avx512.* instructions that take vector(s) of floating-point
5326 // values and perform an operation whose shadow propagation should be handled
5327 // as all-or-nothing [*], with masking provided by a vector and a mask
5328 // supplied as an integer.
5329 //
5330 // [*] if all bits of a vector element are initialized, the output is fully
5331 // initialized; otherwise, the output is fully uninitialized
5332 //
5333 // e.g., <16 x float> @llvm.x86.avx512.rsqrt14.ps.512
5334 // (<16 x float>, <16 x float>, i16)
5335 // A WriteThru Mask
5336 //
5337 // <2 x double> @llvm.x86.avx512.rcp14.pd.128
5338 // (<2 x double>, <2 x double>, i8)
5339 // A WriteThru Mask
5340 //
5341 // <8 x double> @llvm.x86.avx512.mask.rndscale.pd.512
5342 // (<8 x double>, i32, <8 x double>, i8, i32)
5343 // A Imm WriteThru Mask Rounding
5344 //
5345 // <16 x float> @llvm.x86.avx512.mask.scalef.ps.512
5346 // (<16 x float>, <16 x float>, <16 x float>, i16, i32)
5347 // WriteThru A B Mask Rnd
5348 //
5349 // All operands other than A, B, ..., and WriteThru (e.g., Mask, Imm,
5350 // Rounding) must be fully initialized.
5351 //
5352 // Dst[i] = Mask[i] ? some_op(A[i], B[i], ...)
5353 // : WriteThru[i]
5354 // Dst_shadow[i] = Mask[i] ? all_or_nothing(A_shadow[i] | B_shadow[i] | ...)
5355 // : WriteThru_shadow[i]
5356 void handleAVX512VectorGenericMaskedFP(IntrinsicInst &I,
5357 SmallVector<unsigned, 4> DataIndices,
5358 unsigned WriteThruIndex,
5359 unsigned MaskIndex) {
5360 IRBuilder<> IRB(&I);
5361
5362 unsigned NumArgs = I.arg_size();
5363
5364 assert(WriteThruIndex < NumArgs);
5365 assert(MaskIndex < NumArgs);
5366 assert(WriteThruIndex != MaskIndex);
5367 Value *WriteThru = I.getOperand(WriteThruIndex);
5368
5369 unsigned OutputNumElements =
5370 cast<FixedVectorType>(WriteThru->getType())->getNumElements();
5371
5372 assert(DataIndices.size() > 0);
5373
5374 bool isData[16] = {false};
5375 assert(NumArgs <= 16);
5376 for (unsigned i : DataIndices) {
5377 assert(i < NumArgs);
5378 assert(i != WriteThruIndex);
5379 assert(i != MaskIndex);
5380
5381 isData[i] = true;
5382
5383 Value *A = I.getOperand(i);
5384 assert(isFixedFPVector(A));
5385 [[maybe_unused]] unsigned ANumElements =
5386 cast<FixedVectorType>(A->getType())->getNumElements();
5387 assert(ANumElements == OutputNumElements);
5388 }
5389
5390 Value *Mask = I.getOperand(MaskIndex);
5391
5392 assert(isFixedFPVector(WriteThru));
5393
5394 for (unsigned i = 0; i < NumArgs; ++i) {
5395 if (!isData[i] && i != WriteThruIndex) {
5396 // Imm, Mask, Rounding etc. are "control" data, hence we require that
5397 // they be fully initialized.
5398 assert(I.getOperand(i)->getType()->isIntegerTy());
5399 insertCheckShadowOf(I.getOperand(i), &I);
5400 }
5401 }
5402
5403 // The mask has 1 bit per element of A, but a minimum of 8 bits.
5404 if (Mask->getType()->getScalarSizeInBits() == 8 && OutputNumElements < 8)
5405 Mask = IRB.CreateTrunc(Mask, Type::getIntNTy(*MS.C, OutputNumElements));
5406 assert(Mask->getType()->getScalarSizeInBits() == OutputNumElements);
5407
5408 assert(I.getType() == WriteThru->getType());
5409
5410 Mask = IRB.CreateBitCast(
5411 Mask, FixedVectorType::get(IRB.getInt1Ty(), OutputNumElements));
5412
5413 Value *DataShadow = nullptr;
5414 for (unsigned i : DataIndices) {
5415 Value *A = I.getOperand(i);
5416 if (DataShadow)
5417 DataShadow = IRB.CreateOr(DataShadow, getShadow(A));
5418 else
5419 DataShadow = getShadow(A);
5420 }
5421
5422 // All-or-nothing shadow
5423 DataShadow =
5424 IRB.CreateSExt(IRB.CreateICmpNE(DataShadow, getCleanShadow(DataShadow)),
5425 DataShadow->getType());
5426
5427 Value *WriteThruShadow = getShadow(WriteThru);
5428
5429 Value *Shadow = IRB.CreateSelect(Mask, DataShadow, WriteThruShadow);
5430 setShadow(&I, Shadow);
5431
5432 setOriginForNaryOp(I);
5433 }
5434
5435 // AVX512 Floating-Point Classification
5436 //
5437 // e.g.,
5438 // - < 8 x i1> @llvm.x86.avx512.fpclass.pd.512
5439 // (<8 x double> %input, i32 %classifiers)
5440 // - <16 x i1> @llvm.x86.avx512.fpclass.ps.512
5441 // (<16 x float> %input, i32 %classifiers)
5442 void handleAVX512FPClass(IntrinsicInst &I) {
5443 IRBuilder<> IRB(&I);
5444
5445 assert(I.arg_size() == 2);
5446
5447 Value *Input = I.getOperand(0);
5448 assert(isFixedFPVector(Input));
5449 [[maybe_unused]] FixedVectorType *InputType = cast<FixedVectorType>(Input->getType());
5450
5451 Value *Classifiers = I.getOperand(1);
5452 assert(isa<ConstantInt>(Classifiers));
5453 // No shadow check needed for constants
5454
5455 assert(isFixedIntVectorTy(I.getType()));
5456 FixedVectorType *OutputType = cast<FixedVectorType>(I.getType());
5457 assert(OutputType->getScalarSizeInBits() == 1);
5458
5459 assert(OutputType->getNumElements() == InputType->getNumElements());
5460
5461 Value *OutputShadow;
5462 if (cast<ConstantInt>(Classifiers)->isZero())
5463 // Each bit specifies whether a particular classifier is enabled.
5464 // If Classifiers == 0, the output is trivially known to be zero, thus
5465 // the output is fully initialized.
5466 OutputShadow = getCleanShadow(OutputType);
5467 else
5468 // Approximate each bit of the output shadow based on whether the
5469 // corresponding input element is fully initialized. It is only
5470 // approximate because some classifications do not rely on all bits of
5471 // the input element.
5472 OutputShadow = IRB.CreateICmpNE(getShadow(Input), getCleanShadow(Input));
5473
5474 setShadow(&I, OutputShadow);
5475
5476 setOriginForNaryOp(I);
5477 }
5478
5479 // For sh.* compiler intrinsics:
5480 // llvm.x86.avx512fp16.mask.{add/sub/mul/div/max/min}.sh.round
5481 // (<8 x half>, <8 x half>, <8 x half>, i8, i32)
5482 // A B WriteThru Mask RoundingMode
5483 //
5484 // DstShadow[0] = Mask[0] ? (AShadow[0] | BShadow[0]) : WriteThruShadow[0]
5485 // DstShadow[1..7] = AShadow[1..7]
5486 void visitGenericScalarHalfwordInst(IntrinsicInst &I) {
5487 IRBuilder<> IRB(&I);
5488
5489 assert(I.arg_size() == 5);
5490 Value *A = I.getOperand(0);
5491 Value *B = I.getOperand(1);
5492 Value *WriteThrough = I.getOperand(2);
5493 Value *Mask = I.getOperand(3);
5494 Value *RoundingMode = I.getOperand(4);
5495
5496 // Technically, we could probably just check whether the LSB is
5497 // initialized, but intuitively it feels like a partly uninitialized mask
5498 // is unintended, and we should warn the user immediately.
5499 insertCheckShadowOf(Mask, &I);
5500 insertCheckShadowOf(RoundingMode, &I);
5501
5502 assert(isa<FixedVectorType>(A->getType()));
5503 unsigned NumElements =
5504 cast<FixedVectorType>(A->getType())->getNumElements();
5505 assert(NumElements == 8);
5506 assert(A->getType() == B->getType());
5507 assert(B->getType() == WriteThrough->getType());
5508 assert(Mask->getType()->getPrimitiveSizeInBits() == NumElements);
5509 assert(RoundingMode->getType()->isIntegerTy());
5510
5511 Value *ALowerShadow = extractLowerShadow(IRB, A);
5512 Value *BLowerShadow = extractLowerShadow(IRB, B);
5513
5514 Value *ABLowerShadow = IRB.CreateOr(ALowerShadow, BLowerShadow);
5515
5516 Value *WriteThroughLowerShadow = extractLowerShadow(IRB, WriteThrough);
5517
5518 Mask = IRB.CreateBitCast(
5519 Mask, FixedVectorType::get(IRB.getInt1Ty(), NumElements));
5520 Value *MaskLower =
5521 IRB.CreateExtractElement(Mask, ConstantInt::get(IRB.getInt32Ty(), 0));
5522
5523 Value *AShadow = getShadow(A);
5524 Value *DstLowerShadow =
5525 IRB.CreateSelect(MaskLower, ABLowerShadow, WriteThroughLowerShadow);
5526 Value *DstShadow = IRB.CreateInsertElement(
5527 AShadow, DstLowerShadow, ConstantInt::get(IRB.getInt32Ty(), 0),
5528 "_msprop");
5529
5530 setShadow(&I, DstShadow);
5531 setOriginForNaryOp(I);
5532 }
5533
5534 // Approximately handle AVX Galois Field Affine Transformation
5535 //
5536 // e.g.,
5537 // <16 x i8> @llvm.x86.vgf2p8affineqb.128(<16 x i8>, <16 x i8>, i8)
5538 // <32 x i8> @llvm.x86.vgf2p8affineqb.256(<32 x i8>, <32 x i8>, i8)
5539 // <64 x i8> @llvm.x86.vgf2p8affineqb.512(<64 x i8>, <64 x i8>, i8)
5540 // Out A x b
5541 // where A and x are packed matrices, b is a vector,
5542 // Out = A * x + b in GF(2)
5543 //
5544 // Multiplication in GF(2) is equivalent to bitwise AND. However, the matrix
5545 // computation also includes a parity calculation.
5546 //
5547 // For the bitwise AND of bits V1 and V2, the exact shadow is:
5548 // Out_Shadow = (V1_Shadow & V2_Shadow)
5549 // | (V1 & V2_Shadow)
5550 // | (V1_Shadow & V2 )
5551 //
5552 // We approximate the shadow of gf2p8affineqb using:
5553 // Out_Shadow = gf2p8affineqb(x_Shadow, A_shadow, 0)
5554 // | gf2p8affineqb(x, A_shadow, 0)
5555 // | gf2p8affineqb(x_Shadow, A, 0)
5556 // | set1_epi8(b_Shadow)
5557 //
5558 // This approximation has false negatives: if an intermediate dot-product
5559 // contains an even number of 1's, the parity is 0.
5560 // It has no false positives.
5561 void handleAVXGF2P8Affine(IntrinsicInst &I) {
5562 IRBuilder<> IRB(&I);
5563
5564 assert(I.arg_size() == 3);
5565 Value *A = I.getOperand(0);
5566 Value *X = I.getOperand(1);
5567 Value *B = I.getOperand(2);
5568
5569 assert(isFixedIntVector(A));
5570 assert(cast<VectorType>(A->getType())
5571 ->getElementType()
5572 ->getScalarSizeInBits() == 8);
5573
5574 assert(A->getType() == X->getType());
5575
5576 assert(B->getType()->isIntegerTy());
5577 assert(B->getType()->getScalarSizeInBits() == 8);
5578
5579 assert(I.getType() == A->getType());
5580
5581 Value *AShadow = getShadow(A);
5582 Value *XShadow = getShadow(X);
5583 Value *BZeroShadow = getCleanShadow(B);
5584
5585 Value *AShadowXShadow = IRB.CreateIntrinsic(
5586 I.getType(), I.getIntrinsicID(), {XShadow, AShadow, BZeroShadow});
5587 Value *AShadowX = IRB.CreateIntrinsic(I.getType(), I.getIntrinsicID(),
5588 {X, AShadow, BZeroShadow});
5589 Value *XShadowA = IRB.CreateIntrinsic(I.getType(), I.getIntrinsicID(),
5590 {XShadow, A, BZeroShadow});
5591
5592 unsigned NumElements = cast<FixedVectorType>(I.getType())->getNumElements();
5593 Value *BShadow = getShadow(B);
5594 Value *BBroadcastShadow = getCleanShadow(AShadow);
5595 // There is no LLVM IR intrinsic for _mm512_set1_epi8.
5596 // This loop generates a lot of LLVM IR, which we expect that CodeGen will
5597 // lower appropriately (e.g., VPBROADCASTB).
5598 // Besides, b is often a constant, in which case it is fully initialized.
5599 for (unsigned i = 0; i < NumElements; i++)
5600 BBroadcastShadow = IRB.CreateInsertElement(BBroadcastShadow, BShadow, i);
5601
5602 setShadow(&I, IRB.CreateOr(
5603 {AShadowXShadow, AShadowX, XShadowA, BBroadcastShadow}));
5604 setOriginForNaryOp(I);
5605 }
5606
5607 // Handle Arm NEON vector load intrinsics (vld*).
5608 //
5609 // The WithLane instructions (ld[234]lane) are similar to:
5610 // call {<4 x i32>, <4 x i32>, <4 x i32>}
5611 // @llvm.aarch64.neon.ld3lane.v4i32.p0
5612 // (<4 x i32> %L1, <4 x i32> %L2, <4 x i32> %L3, i64 %lane, ptr
5613 // %A)
5614 //
5615 // The non-WithLane instructions (ld[234], ld1x[234], ld[234]r) are similar
5616 // to:
5617 // call {<8 x i8>, <8 x i8>} @llvm.aarch64.neon.ld2.v8i8.p0(ptr %A)
5618 void handleNEONVectorLoad(IntrinsicInst &I, bool WithLane) {
5619 unsigned int numArgs = I.arg_size();
5620
5621 // Return type is a struct of vectors of integers or floating-point
5622 assert(I.getType()->isStructTy());
5623 [[maybe_unused]] StructType *RetTy = cast<StructType>(I.getType());
5624 assert(RetTy->getNumElements() > 0);
5626 RetTy->getElementType(0)->isFPOrFPVectorTy());
5627 for (unsigned int i = 0; i < RetTy->getNumElements(); i++)
5628 assert(RetTy->getElementType(i) == RetTy->getElementType(0));
5629
5630 if (WithLane) {
5631 // 2, 3 or 4 vectors, plus lane number, plus input pointer
5632 assert(4 <= numArgs && numArgs <= 6);
5633
5634 // Return type is a struct of the input vectors
5635 assert(RetTy->getNumElements() + 2 == numArgs);
5636 for (unsigned int i = 0; i < RetTy->getNumElements(); i++)
5637 assert(I.getArgOperand(i)->getType() == RetTy->getElementType(0));
5638 } else {
5639 assert(numArgs == 1);
5640 }
5641
5642 IRBuilder<> IRB(&I);
5643
5644 SmallVector<Value *, 6> ShadowArgs;
5645 if (WithLane) {
5646 for (unsigned int i = 0; i < numArgs - 2; i++)
5647 ShadowArgs.push_back(getShadow(I.getArgOperand(i)));
5648
5649 // Lane number, passed verbatim
5650 Value *LaneNumber = I.getArgOperand(numArgs - 2);
5651 ShadowArgs.push_back(LaneNumber);
5652
5653 // TODO: blend shadow of lane number into output shadow?
5654 insertCheckShadowOf(LaneNumber, &I);
5655 }
5656
5657 Value *Src = I.getArgOperand(numArgs - 1);
5658 assert(Src->getType()->isPointerTy() && "Source is not a pointer!");
5659
5660 Type *SrcShadowTy = getShadowTy(Src);
5661 auto [SrcShadowPtr, SrcOriginPtr] =
5662 getShadowOriginPtr(Src, IRB, SrcShadowTy, Align(1), /*isStore*/ false);
5663 ShadowArgs.push_back(SrcShadowPtr);
5664
5665 // The NEON vector load instructions handled by this function all have
5666 // integer variants. It is easier to use those rather than trying to cast
5667 // a struct of vectors of floats into a struct of vectors of integers.
5668 CallInst *CI = IRB.CreateIntrinsicWithoutFolding(
5669 getShadowTy(&I), I.getIntrinsicID(), ShadowArgs);
5670 setShadow(&I, CI);
5671
5672 if (!MS.TrackOrigins)
5673 return;
5674
5675 Value *PtrSrcOrigin = IRB.CreateLoad(MS.OriginTy, SrcOriginPtr);
5676 setOrigin(&I, PtrSrcOrigin);
5677 }
5678
5679 /// Handle Arm NEON vector store intrinsics (vst{2,3,4}, vst1x_{2,3,4},
5680 /// and vst{2,3,4}lane).
5681 ///
5682 /// Arm NEON vector store intrinsics have the output address (pointer) as the
5683 /// last argument, with the initial arguments being the inputs (and lane
5684 /// number for vst{2,3,4}lane). They return void.
5685 ///
5686 /// - st4 interleaves the output e.g., st4 (inA, inB, inC, inD, outP) writes
5687 /// abcdabcdabcdabcd... into *outP
5688 /// - st1_x4 is non-interleaved e.g., st1_x4 (inA, inB, inC, inD, outP)
5689 /// writes aaaa...bbbb...cccc...dddd... into *outP
5690 /// - st4lane has arguments of (inA, inB, inC, inD, lane, outP)
5691 /// These instructions can all be instrumented with essentially the same
5692 /// MSan logic, simply by applying the corresponding intrinsic to the shadow.
5693 void handleNEONVectorStoreIntrinsic(IntrinsicInst &I, bool useLane) {
5694 IRBuilder<> IRB(&I);
5695
5696 // Don't use getNumOperands() because it includes the callee
5697 int numArgOperands = I.arg_size();
5698
5699 // The last arg operand is the output (pointer)
5700 assert(numArgOperands >= 1);
5701 Value *Addr = I.getArgOperand(numArgOperands - 1);
5702 assert(Addr->getType()->isPointerTy());
5703 int skipTrailingOperands = 1;
5704
5705 if (Opts.msan_check_access_address)
5706 insertCheckShadowOf(Addr, &I);
5707
5708 // Second-last operand is the lane number (for vst{2,3,4}lane)
5709 if (useLane) {
5710 skipTrailingOperands++;
5711 assert(numArgOperands >= static_cast<int>(skipTrailingOperands));
5713 I.getArgOperand(numArgOperands - skipTrailingOperands)->getType()));
5714 }
5715
5716 SmallVector<Value *, 8> ShadowArgs;
5717 // All the initial operands are the inputs
5718 for (int i = 0; i < numArgOperands - skipTrailingOperands; i++) {
5719 assert(isa<FixedVectorType>(I.getArgOperand(i)->getType()));
5720 Value *Shadow = getShadow(&I, i);
5721 ShadowArgs.append(1, Shadow);
5722 }
5723
5724 // MSan's GetShadowTy assumes the LHS is the type we want the shadow for
5725 // e.g., for:
5726 // [[TMP5:%.*]] = bitcast <16 x i8> [[TMP2]] to i128
5727 // we know the type of the output (and its shadow) is <16 x i8>.
5728 //
5729 // Arm NEON VST is unusual because the last argument is the output address:
5730 // define void @st2_16b(<16 x i8> %A, <16 x i8> %B, ptr %P) {
5731 // call void @llvm.aarch64.neon.st2.v16i8.p0
5732 // (<16 x i8> [[A]], <16 x i8> [[B]], ptr [[P]])
5733 // and we have no type information about P's operand. We must manually
5734 // compute the type (<16 x i8> x 2).
5735 FixedVectorType *OutputVectorTy = FixedVectorType::get(
5736 cast<FixedVectorType>(I.getArgOperand(0)->getType())->getElementType(),
5737 cast<FixedVectorType>(I.getArgOperand(0)->getType())->getNumElements() *
5738 (numArgOperands - skipTrailingOperands));
5739 Type *OutputShadowTy = getShadowTy(OutputVectorTy);
5740
5741 if (useLane)
5742 ShadowArgs.append(1,
5743 I.getArgOperand(numArgOperands - skipTrailingOperands));
5744
5745 Value *OutputShadowPtr, *OutputOriginPtr;
5746 // AArch64 NEON does not need alignment (unless OS requires it)
5747 std::tie(OutputShadowPtr, OutputOriginPtr) = getShadowOriginPtr(
5748 Addr, IRB, OutputShadowTy, Align(1), /*isStore*/ true);
5749 ShadowArgs.append(1, OutputShadowPtr);
5750
5751 CallInst *CI = IRB.CreateIntrinsicWithoutFolding(
5752 IRB.getVoidTy(), I.getIntrinsicID(), ShadowArgs);
5753 setShadow(&I, CI);
5754
5755 if (MS.TrackOrigins) {
5756 // TODO: if we modelled the vst* instruction more precisely, we could
5757 // more accurately track the origins (e.g., if both inputs are
5758 // uninitialized for vst2, we currently blame the second input, even
5759 // though part of the output depends only on the first input).
5760 //
5761 // This is particularly imprecise for vst{2,3,4}lane, since only one
5762 // lane of each input is actually copied to the output.
5763 OriginCombiner OC(this, IRB);
5764 for (int i = 0; i < numArgOperands - skipTrailingOperands; i++)
5765 OC.Add(I.getArgOperand(i));
5766
5767 const DataLayout &DL = F.getDataLayout();
5768 OC.DoneAndStoreOrigin(DL.getTypeStoreSize(OutputVectorTy),
5769 OutputOriginPtr);
5770 }
5771 }
5772
5773 // Integer matrix multiplication:
5774 // - <4 x i32> @llvm.aarch64.neon.{s,u,us}mmla.v4i32.v16i8
5775 // (<4 x i32> %R, <16 x i8> %A, <16 x i8> %B)
5776 // - <4 x i32> is a 2x2 matrix
5777 // - <16 x i8> %A and %B are 2x8 and 8x2 matrices respectively
5778 //
5779 // Floating-point matrix multiplication:
5780 // - <4 x float> @llvm.aarch64.neon.bfmmla
5781 // (<4 x float> %R, <8 x bfloat> %A, <8 x bfloat> %B)
5782 // - <4 x float> is a 2x2 matrix
5783 // - <8 x bfloat> %A and %B are 2x4 and 4x2 matrices respectively
5784 //
5785 // The general shadow propagation approach is:
5786 // 1) get the shadows of the input matrices %A and %B
5787 // 2) map each shadow value to 0x1 if the corresponding value is fully
5788 // initialized, and 0x0 otherwise
5789 // 3) perform a matrix multiplication on the shadows of %A and %B [*].
5790 // The output will be a 2x2 matrix. For each element, a value of 0x8
5791 // (for {s,u,us}mmla) or 0x4 (for bfmmla) means all the corresponding
5792 // inputs were clean; if so, set the shadow to zero, otherwise set to -1.
5793 // 4) blend in the shadow of %R
5794 //
5795 // [*] Since shadows are integral, the obvious approach is to always apply
5796 // ummla to the shadows. Unfortunately, Armv8.2+bf16 supports bfmmla,
5797 // but not ummla. Thus, for bfmmla, our instrumentation reuses bfmmla.
5798 //
5799 // TODO: consider allowing multiplication of zero with an uninitialized value
5800 // to result in an initialized value.
5801 void handleNEONMatrixMultiply(IntrinsicInst &I) {
5802 IRBuilder<> IRB(&I);
5803
5804 assert(I.arg_size() == 3);
5805 Value *R = I.getArgOperand(0);
5806 Value *A = I.getArgOperand(1);
5807 Value *B = I.getArgOperand(2);
5808
5809 assert(I.getType() == R->getType());
5810
5811 assert(isa<FixedVectorType>(R->getType()));
5812 assert(isa<FixedVectorType>(A->getType()));
5813 assert(isa<FixedVectorType>(B->getType()));
5814
5815 FixedVectorType *RTy = cast<FixedVectorType>(R->getType());
5816 FixedVectorType *ATy = cast<FixedVectorType>(A->getType());
5817 FixedVectorType *BTy = cast<FixedVectorType>(B->getType());
5818 assert(ATy->getElementType() == BTy->getElementType());
5819
5820 if (RTy->getElementType()->isIntegerTy()) {
5821 // <4 x i32> @llvm.aarch64.neon.ummla.v4i32.v16i8
5822 // (<4 x i32> %R, <16 x i8> %X, <16 x i8> %Y)
5823 assert(RTy == FixedVectorType::get(IntegerType::get(*MS.C, 32), 4));
5824 assert(ATy == FixedVectorType::get(IntegerType::get(*MS.C, 8), 16));
5825 assert(BTy == FixedVectorType::get(IntegerType::get(*MS.C, 8), 16));
5826 } else {
5827 // <4 x float> @llvm.aarch64.neon.bfmmla
5828 // (<4 x float> %R, <8 x bfloat> %X, <8 x bfloat> %Y)
5829 assert(RTy == FixedVectorType::get(Type::getFloatTy(*MS.C), 4));
5830 assert(ATy == FixedVectorType::get(Type::getBFloatTy(*MS.C), 8));
5831 assert(BTy == FixedVectorType::get(Type::getBFloatTy(*MS.C), 8));
5832 }
5833
5834 Value *ShadowR = getShadow(&I, 0);
5835 Value *ShadowA = getShadow(&I, 1);
5836 Value *ShadowB = getShadow(&I, 2);
5837
5838 Value *ShadowAB;
5839 Value *FullyInit;
5840
5841 if (RTy->getElementType()->isIntegerTy()) {
5842 // If the value is fully initialized, the shadow will be 000...001.
5843 // Otherwise, the shadow will be all zero.
5844 // (This is the opposite of how we typically handle shadows.)
5845 ShadowA = IRB.CreateZExt(IRB.CreateICmpEQ(ShadowA, getCleanShadow(ATy)),
5846 getShadowTy(ATy));
5847 ShadowB = IRB.CreateZExt(IRB.CreateICmpEQ(ShadowB, getCleanShadow(BTy)),
5848 getShadowTy(BTy));
5849 // TODO: the CreateSelect approach used below for floating-point is more
5850 // generic than CreateZExt. Investigate whether it is worthwhile
5851 // unifying the two approaches.
5852
5853 ShadowAB = IRB.CreateIntrinsic(RTy, Intrinsic::aarch64_neon_ummla,
5854 {getCleanShadow(RTy), ShadowA, ShadowB});
5855
5856 // ummla multiplies a 2x8 matrix with an 8x2 matrix. If all entries of the
5857 // input matrices are equal to 0x1, all entries of the output matrix will
5858 // be 0x8.
5859 FullyInit = ConstantVector::getSplat(
5860 RTy->getElementCount(), ConstantInt::get(RTy->getElementType(), 0x8));
5861
5862 ShadowAB = IRB.CreateICmpNE(ShadowAB, FullyInit);
5863 } else {
5865 ATy->getElementCount(), ConstantFP::get(ATy->getElementType(), 0));
5867 ATy->getElementCount(), ConstantFP::get(ATy->getElementType(), 1));
5868
5869 // As per the integer case, if the shadow is clean, we store 0x1,
5870 // otherwise we store 0x0 (the opposite of usual shadow arithmetic).
5871 ShadowA = IRB.CreateSelect(IRB.CreateICmpEQ(ShadowA, getCleanShadow(ATy)),
5872 ABOnes, ABZeros);
5873 ShadowB = IRB.CreateSelect(IRB.CreateICmpEQ(ShadowB, getCleanShadow(BTy)),
5874 ABOnes, ABZeros);
5875
5877 RTy->getElementCount(), ConstantFP::get(RTy->getElementType(), 0));
5878
5879 ShadowAB = IRB.CreateIntrinsic(RTy, Intrinsic::aarch64_neon_bfmmla,
5880 {RZeros, ShadowA, ShadowB});
5881
5882 // bfmmla multiplies a 2x4 matrix with an 4x2 matrix. If all entries of
5883 // the input matrices are equal to 0x1, all entries of the output matrix
5884 // will be 4.0. (To avoid floating-point error, we check if each entry
5885 // < 3.5.)
5886 FullyInit = ConstantVector::getSplat(
5887 RTy->getElementCount(), ConstantFP::get(RTy->getElementType(), 3.5));
5888
5889 // FCmpULT: "yields true if either operand is a QNAN or op1 is less than"
5890 // op2"
5891 ShadowAB = IRB.CreateFCmpULT(ShadowAB, FullyInit);
5892 }
5893
5894 ShadowR = IRB.CreateICmpNE(ShadowR, getCleanShadow(RTy));
5895 ShadowR = IRB.CreateOr(ShadowAB, ShadowR);
5896
5897 setShadow(&I, IRB.CreateSExt(ShadowR, getShadowTy(RTy)));
5898
5899 setOriginForNaryOp(I);
5900 }
5901
5902 /// Handle intrinsics by applying the intrinsic to the shadows.
5903 ///
5904 /// For example, this can be applied to the Arm NEON vector table intrinsics
5905 /// (tbl{1,2,3,4}).
5906 ///
5907 /// Typically, shadowIntrinsicID will be specified by the caller to be
5908 /// I.getIntrinsicID(), but the caller can choose to replace it with another
5909 /// intrinsic of the same type.
5910 ///
5911 /// verbatimArgIndices specifies which arguments are passed unmodified to the
5912 /// intrinsic, though such arguments will also taint the shadow. Non-negative
5913 /// indices are zero-indexed, while negative indices count from the last
5914 /// argument. For example, if an intrinsic has one trailing verbatim argument
5915 /// (specified with verbatimArgIndices = {-1}):
5916 /// out = intrinsic(var1, var2, opType)
5917 /// we compute:
5918 /// shadow[out] =
5919 /// intrinsic(shadow[var1], shadow[var2], opType) | shadow[opType]
5920 ///
5921 /// If an intrinsic is called with floating-point arguments, we will
5922 /// typically cast the shadows to floating-point, apply the intrinsic [*],
5923 /// then cast the result back to integer/shadow.
5924 ///
5925 /// In cases where we know the intrinsic is compatible with integer
5926 /// arguments, 'forceIntegerIntrinsic' will apply the integer variant, even
5927 /// if the arguments are floating-point, thus avoiding unnecessary casts
5928 /// e.g., if I is:
5929 /// <16 x float> @llvm.x86.avx512.mask.compress
5930 /// (<16 x float>, <16 x float>, <16 x i1> %mask)
5931 /// we would prefer to compute the shadows using:
5932 /// <16 x i32> @llvm.x86.avx512.mask.compress
5933 /// (<16 x i32>, <16 x i32>, <16 x i1> %mask)
5934 ///
5935 /// [*] CAUTION: this assumes that the intrinsic will handle arbitrary
5936 /// bit-patterns (for example, if the intrinsic accepts floats
5937 /// for var1, we require that it doesn't care if inputs are
5938 /// NaNs).
5939 ///
5940 /// The origin is approximated using setOriginForNaryOp.
5941 void handleIntrinsicByApplyingToShadow(IntrinsicInst &I,
5942 Intrinsic::ID shadowIntrinsicID,
5943 ArrayRef<int> verbatimArgIndices,
5944 bool forceIntegerIntrinsic) {
5945 IRBuilder<> IRB(&I);
5946
5947 assert(verbatimArgIndices.size() <= I.arg_size());
5948
5949 // verbatimArgIndices may have negative indices, and the indices may be in
5950 // any order (e.g., [5, -1, 2]). Convert it to a lookup table.
5951 SmallVector<bool, 4> verbatimArgLookup(I.arg_size(), false);
5952
5953 for (int index : verbatimArgIndices) {
5954 if (index < 0)
5955 index += I.arg_size();
5956 assert(index >= 0 && static_cast<unsigned int>(index) < I.arg_size());
5957 verbatimArgLookup[index] = true;
5958 }
5959
5960 SmallVector<Value *, 8> ShadowArgs;
5961 // Don't use getNumOperands() because it includes the callee
5962 for (unsigned int i = 0; i < I.arg_size(); i++) {
5963 if (verbatimArgLookup[i]) {
5964 Value *Arg = I.getArgOperand(i);
5965
5966 if (forceIntegerIntrinsic)
5968
5969 ShadowArgs.push_back(Arg);
5970 } else {
5971 Value *Shadow = getShadow(&I, i);
5972
5973 if (forceIntegerIntrinsic)
5974 ShadowArgs.push_back(Shadow);
5975 else
5976 ShadowArgs.push_back(
5977 IRB.CreateBitCast(Shadow, I.getArgOperand(i)->getType()));
5978 }
5979 }
5980
5981 Value *CombinedShadow;
5982 if (forceIntegerIntrinsic) {
5983 CombinedShadow =
5984 IRB.CreateIntrinsic(getShadowTy(&I), shadowIntrinsicID, ShadowArgs);
5985 } else {
5986 Value *CI =
5987 IRB.CreateIntrinsic(I.getType(), shadowIntrinsicID, ShadowArgs);
5988 CombinedShadow = IRB.CreateBitCast(CI, getShadowTy(&I));
5989 }
5990
5991 // Combine the computed shadow with the shadow of verbatim args
5992 //
5993 // N.B. we could merge this with the earlier loop, but we keep it separate
5994 // for the IR to be byte-identical with the existing tests.
5995 for (unsigned int i = 0; i < I.arg_size(); i++) {
5996 if (!verbatimArgLookup[i])
5997 continue;
5998
5999 Value *Shadow =
6000 CreateShadowCast(IRB, getShadow(&I, i), CombinedShadow->getType());
6001 CombinedShadow = IRB.CreateOr(Shadow, CombinedShadow, "_msprop");
6002 }
6003
6004 setShadow(&I, CombinedShadow);
6005
6006 setOriginForNaryOp(I);
6007 }
6008
6009 // Approximation only
6010 //
6011 // e.g., <16 x i8> @llvm.aarch64.neon.pmull64(i64, i64)
6012 void handleNEONVectorMultiplyIntrinsic(IntrinsicInst &I) {
6013 assert(I.arg_size() == 2);
6014
6015 handleShadowOr(I);
6016 }
6017
6018 // Handles:
6019 // <4 x half> @llvm.aarch64.neon.fp8.fdot2.lane
6020 // (<4 x half>, <8 x i8>, <16 x i8>, i32)
6021 // accumulator A B lane
6022 //
6023 // <8 x half> @llvm.aarch64.neon.fp8.fdot2.lane
6024 // (<8 x half>, <16 x i8>, <16 x i8>, i32)
6025 // <2 x float> @llvm.aarch64.neon.fp8.fdot4.lane
6026 // (<2 x float>, <8 x i8>, <16 x i8>, i32)
6027 // <4 x float> @llvm.aarch64.neon.fp8.fdot4.lane
6028 // (<4 x float>, <16 x i8>, <16 x i8>, i32)
6029 //
6030 // The lane specifies which pair (fdot2) or quad (fdot4) of numbers to
6031 // extract from B, which is then splatted before being used in the dot
6032 // products e.g., for
6033 // <4 x half> @llvm.aarch64.neon.fp8.fdot2.lane:
6034 // (<4 x half>, <8 x i8>, <16 x i8>, 1)
6035 //
6036 // acc[0] acc[1] acc[2] acc[3]
6037 // + + + + + + + +
6038 // A[0] A[1] A[2] A[3] A[4] A[5] A[6] A[7]
6039 // * * * * * * * *
6040 // B[2] B[3] B[2] B[3] B[2] B[3] B[2] B[3]
6041 //
6042 // Notice that if any bit of B[2] or B[3] is uninitialized, every accumulator
6043 // value will become tainted; we approximate this by marking the output as
6044 // fully uninitialized. This permits a 'Select' optimization.
6045 //
6046 // This function is separate from handleVectorDotProductIntrinsic(), because
6047 // the non-overlapping features (e.g., odd/even lanes vs. numbered lanes,
6048 // ZeroPurifies, EltSizeInBits) and optimizations make clean code reuse
6049 // difficult.
6050 void handleNEONDotProductLaneIntrinsic(IntrinsicInst &I,
6051 unsigned ReductionFactor) {
6052 IRBuilder<> IRB(&I);
6053 assert(I.arg_size() == 4);
6054
6055 [[maybe_unused]] Value *VAcc = I.getOperand(0);
6056 [[maybe_unused]] Value *Va = I.getOperand(1);
6057 [[maybe_unused]] Value *Vb = I.getOperand(2);
6058 Value *Lane = I.getOperand(3);
6059
6061 assert(VAcc->getType() == I.getType());
6062
6065 I.getType()->getPrimitiveSizeInBits());
6066
6067 assert(cast<FixedVectorType>(Va->getType())->getNumElements() ==
6068 cast<FixedVectorType>(I.getType())->getNumElements() *
6069 ReductionFactor);
6070
6072 // Deliberately not strict equality
6074 I.getType()->getPrimitiveSizeInBits());
6075
6076 assert(Lane->getType()->isIntegerTy());
6077
6078 // (<4 x 16>, <8 x i8>, <16 x i8>)
6079 // SAcc Sa Sb
6080 Value *SAcc = getShadow(&I, 0);
6081 Value *Sa = getShadow(&I, 1);
6082 Value *Sb = getShadow(&I, 2);
6083
6084 // Cast the shadows to:
6085 // (<4 x i16>, <4 x i16>, <8 x i16>)
6086 // SAcc Sa Sb
6087 Sa = IRB.CreateBitCast(Sa, SAcc->getType());
6088 Sb = IRB.CreateBitCast(
6089 Sb, FixedVectorType::getWithSizeAndScalar(
6091 cast<FixedVectorType>(SAcc->getType())->getElementType()));
6092
6093 // All-or-nothing shadows
6094 Sa =
6095 IRB.CreateSExt(IRB.CreateICmpNE(Sa, getCleanShadow(Sa)), Sa->getType());
6096
6097 // Extract the specific lane from Sb to get i16, then turn it into a single
6098 // bit representing if it is fully initialized.
6099 Sb = IRB.CreateExtractElement(Sb, Lane);
6100 Value *SbClean = IRB.CreateIsNull(Sb);
6101
6102 Value *SOutput = IRB.CreateOr(SAcc, Sa);
6103
6104 // Select is cheaper than broadcasting Sb into <4 x i16>.
6105 SOutput = IRB.CreateSelect(SbClean, SOutput, getPoisonedShadow(SOutput));
6106
6107 setShadow(&I, SOutput);
6108 setOriginForNaryOp(I);
6109 }
6110
6111 bool maybeHandleCrossPlatformIntrinsic(IntrinsicInst &I) {
6112 switch (I.getIntrinsicID()) {
6113 case Intrinsic::uadd_with_overflow:
6114 case Intrinsic::sadd_with_overflow:
6115 case Intrinsic::usub_with_overflow:
6116 case Intrinsic::ssub_with_overflow:
6117 case Intrinsic::umul_with_overflow:
6118 case Intrinsic::smul_with_overflow:
6119 handleArithmeticWithOverflow(I);
6120 break;
6121 case Intrinsic::modf:
6122 case Intrinsic::sincos:
6123 case Intrinsic::sincospi:
6124 handleModfOrSincos(I);
6125 break;
6126 case Intrinsic::abs:
6127 handleAbsIntrinsic(I);
6128 break;
6129 case Intrinsic::bitreverse:
6130 handleIntrinsicByApplyingToShadow(I, I.getIntrinsicID(),
6131 /*verbatimArgIndices=*/{},
6132 /*forceIntegerIntrinsic=*/false);
6133 break;
6134 case Intrinsic::is_fpclass:
6135 handleIsFpClass(I);
6136 break;
6137 case Intrinsic::lifetime_start:
6138 handleLifetimeStart(I);
6139 break;
6140 case Intrinsic::launder_invariant_group:
6141 handleInvariantGroup(I);
6142 break;
6143 case Intrinsic::bswap:
6144 handleBswap(I);
6145 break;
6146 case Intrinsic::ctlz:
6147 case Intrinsic::cttz:
6148 handleCountLeadingTrailingZeros(I);
6149 break;
6150 case Intrinsic::masked_compressstore:
6151 handleMaskedCompressStore(I);
6152 break;
6153 case Intrinsic::masked_expandload:
6154 handleMaskedExpandLoad(I);
6155 break;
6156 case Intrinsic::masked_gather:
6157 handleMaskedGather(I);
6158 break;
6159 case Intrinsic::masked_scatter:
6160 handleMaskedScatter(I);
6161 break;
6162 case Intrinsic::masked_store:
6163 handleMaskedStore(I);
6164 break;
6165 case Intrinsic::masked_load:
6166 handleMaskedLoad(I);
6167 break;
6168 case Intrinsic::masked_udiv:
6169 case Intrinsic::masked_sdiv:
6170 case Intrinsic::masked_urem:
6171 case Intrinsic::masked_srem:
6172 handleMaskedIntegerDivRem(I);
6173 break;
6174 case Intrinsic::vector_reduce_and:
6175 handleVectorReduceAndIntrinsic(I);
6176 break;
6177 case Intrinsic::vector_reduce_or:
6178 handleVectorReduceOrIntrinsic(I);
6179 break;
6180
6181 case Intrinsic::vector_reduce_add:
6182 case Intrinsic::vector_reduce_xor:
6183 case Intrinsic::vector_reduce_mul:
6184 // Signed/Unsigned Min/Max
6185 // TODO: handling similarly to AND/OR may be more precise.
6186 case Intrinsic::vector_reduce_smax:
6187 case Intrinsic::vector_reduce_smin:
6188 case Intrinsic::vector_reduce_umax:
6189 case Intrinsic::vector_reduce_umin:
6190 // TODO: this has no false positives, but arguably we should check that all
6191 // the bits are initialized.
6192 case Intrinsic::vector_reduce_fmax:
6193 case Intrinsic::vector_reduce_fmin:
6194 handleVectorReduceIntrinsic(I, /*AllowShadowCast=*/false);
6195 break;
6196
6197 case Intrinsic::vector_reduce_fadd:
6198 case Intrinsic::vector_reduce_fmul:
6199 handleVectorReduceWithStarterIntrinsic(I);
6200 break;
6201
6202 // e.g., <4 x i32> @llvm.vector.partial.reduce.add(<4 x i32>, <8 x i32>)
6203 case Intrinsic::vector_partial_reduce_add:
6204 case Intrinsic::vector_partial_reduce_fadd:
6205 handleVectorPartialReduceAddIntrinsic(I);
6206 break;
6207
6208 case Intrinsic::experimental_vector_extract_last_active:
6209 handleVectorExtractLastActive(I);
6210 break;
6211
6212 case Intrinsic::scmp:
6213 case Intrinsic::ucmp: {
6214 handleShadowOr(I);
6215 break;
6216 }
6217
6218 case Intrinsic::fshl:
6219 case Intrinsic::fshr:
6220 handleFunnelShift(I);
6221 break;
6222
6223 case Intrinsic::pdep:
6224 case Intrinsic::pext:
6225 handleGenericBitManipulation(I);
6226 break;
6227
6228 case Intrinsic::is_constant:
6229 // The result of llvm.is.constant() is always defined.
6230 setShadow(&I, getCleanShadow(&I));
6231 setOrigin(&I, getCleanOrigin());
6232 break;
6233
6234 // The non-saturating versions are handled by visitFPTo[US]IInst().
6235 //
6236 // N.B. some platform-specific intrinsics, such as AArch64 fcvtz[us], are
6237 // lowered to these cross-platform intrinsics.
6238 case Intrinsic::fptosi_sat:
6239 case Intrinsic::fptoui_sat:
6240 handleGenericVectorConvertIntrinsic(I, /*FixedPoint=*/false);
6241 break;
6242
6243 // e.g.,
6244 // notail call void (...) @llvm.fake.use(i64 %x)
6245 // notail call void (...) @llvm.fake.use(i32 %y)
6246 // notail call void (...) @llvm.fake.use(ptr %z)
6247 case Intrinsic::fake_use:
6248 assert(I.getType()->isVoidTy());
6249 // fake_uses aren't real, they can't hurt you. If the use isn't real, it
6250 // can't be a real use-of-uninitialized memory. Silently skip over
6251 // fake_use.
6252 return true;
6253
6254 default:
6255 return false;
6256 }
6257
6258 return true;
6259 }
6260
6261 bool maybeHandleX86SIMDIntrinsic(IntrinsicInst &I) {
6262 switch (I.getIntrinsicID()) {
6263 case Intrinsic::x86_sse_stmxcsr:
6264 handleStmxcsr(I);
6265 break;
6266 case Intrinsic::x86_sse_ldmxcsr:
6267 handleLdmxcsr(I);
6268 break;
6269
6270 // Convert Scalar Double Precision Floating-Point Value
6271 // to Unsigned Doubleword Integer
6272 // etc.
6273 case Intrinsic::x86_avx512_vcvtsd2usi64:
6274 case Intrinsic::x86_avx512_vcvtsd2usi32:
6275 case Intrinsic::x86_avx512_vcvtss2usi64:
6276 case Intrinsic::x86_avx512_vcvtss2usi32:
6277 case Intrinsic::x86_avx512_cvttss2usi64:
6278 case Intrinsic::x86_avx512_cvttss2usi:
6279 case Intrinsic::x86_avx512_cvttsd2usi64:
6280 case Intrinsic::x86_avx512_cvttsd2usi:
6281 case Intrinsic::x86_avx512_cvtusi2ss:
6282 case Intrinsic::x86_avx512_cvtusi642sd:
6283 case Intrinsic::x86_avx512_cvtusi642ss:
6284 handleSSEVectorConvertIntrinsic(I, 1, true);
6285 break;
6286 case Intrinsic::x86_sse2_cvtsd2si64:
6287 case Intrinsic::x86_sse2_cvtsd2si:
6288 case Intrinsic::x86_sse2_cvtsd2ss:
6289 case Intrinsic::x86_sse2_cvttsd2si64:
6290 case Intrinsic::x86_sse2_cvttsd2si:
6291 case Intrinsic::x86_sse_cvtss2si64:
6292 case Intrinsic::x86_sse_cvtss2si:
6293 case Intrinsic::x86_sse_cvttss2si64:
6294 case Intrinsic::x86_sse_cvttss2si:
6295 handleSSEVectorConvertIntrinsic(I, 1);
6296 break;
6297 case Intrinsic::x86_sse_cvtps2pi:
6298 case Intrinsic::x86_sse_cvttps2pi:
6299 handleSSEVectorConvertIntrinsic(I, 2);
6300 break;
6301
6302 // TODO:
6303 // <1 x i64> @llvm.x86.sse.cvtpd2pi(<2 x double>)
6304 // <2 x double> @llvm.x86.sse.cvtpi2pd(<1 x i64>)
6305 // <4 x float> @llvm.x86.sse.cvtpi2ps(<4 x float>, <1 x i64>)
6306
6307 case Intrinsic::x86_vcvtps2ph_128:
6308 case Intrinsic::x86_vcvtps2ph_256: {
6309 handleSSEVectorConvertIntrinsicByProp(I, /*HasRoundingMode=*/true);
6310 break;
6311 }
6312
6313 // Convert Packed Single Precision Floating-Point Values
6314 // to Packed Signed Doubleword Integer Values
6315 //
6316 // <16 x i32> @llvm.x86.avx512.mask.cvtps2dq.512
6317 // (<16 x float>, <16 x i32>, i16, i32)
6318 case Intrinsic::x86_avx512_mask_cvtps2dq_512:
6319 handleAVX512VectorConvertFPToInt(I, /*LastMask=*/false);
6320 break;
6321
6322 // Convert Packed Double Precision Floating-Point Values
6323 // to Packed Single Precision Floating-Point Values
6324 case Intrinsic::x86_sse2_cvtpd2ps:
6325 case Intrinsic::x86_sse2_cvtps2dq:
6326 case Intrinsic::x86_sse2_cvtpd2dq:
6327 case Intrinsic::x86_sse2_cvttps2dq:
6328 case Intrinsic::x86_sse2_cvttpd2dq:
6329 case Intrinsic::x86_avx_cvt_pd2_ps_256:
6330 case Intrinsic::x86_avx_cvt_ps2dq_256:
6331 case Intrinsic::x86_avx_cvt_pd2dq_256:
6332 case Intrinsic::x86_avx_cvtt_ps2dq_256:
6333 case Intrinsic::x86_avx_cvtt_pd2dq_256: {
6334 handleSSEVectorConvertIntrinsicByProp(I, /*HasRoundingMode=*/false);
6335 break;
6336 }
6337
6338 // Convert Single-Precision FP Value to 16-bit FP Value
6339 // <16 x i16> @llvm.x86.avx512.mask.vcvtps2ph.512
6340 // (<16 x float>, i32, <16 x i16>, i16)
6341 // <8 x i16> @llvm.x86.avx512.mask.vcvtps2ph.128
6342 // (<4 x float>, i32, <8 x i16>, i8)
6343 // <8 x i16> @llvm.x86.avx512.mask.vcvtps2ph.256
6344 // (<8 x float>, i32, <8 x i16>, i8)
6345 case Intrinsic::x86_avx512_mask_vcvtps2ph_512:
6346 case Intrinsic::x86_avx512_mask_vcvtps2ph_256:
6347 case Intrinsic::x86_avx512_mask_vcvtps2ph_128:
6348 handleAVX512VectorConvertFPToInt(I, /*LastMask=*/true);
6349 break;
6350
6351 // Shift Packed Data (Left Logical, Right Arithmetic, Right Logical)
6352 case Intrinsic::x86_avx512_psll_w_512:
6353 case Intrinsic::x86_avx512_psll_d_512:
6354 case Intrinsic::x86_avx512_psll_q_512:
6355 case Intrinsic::x86_avx512_pslli_w_512:
6356 case Intrinsic::x86_avx512_pslli_d_512:
6357 case Intrinsic::x86_avx512_pslli_q_512:
6358 case Intrinsic::x86_avx512_psrl_w_512:
6359 case Intrinsic::x86_avx512_psrl_d_512:
6360 case Intrinsic::x86_avx512_psrl_q_512:
6361 case Intrinsic::x86_avx512_psra_w_512:
6362 case Intrinsic::x86_avx512_psra_d_512:
6363 case Intrinsic::x86_avx512_psra_q_512:
6364 case Intrinsic::x86_avx512_psrli_w_512:
6365 case Intrinsic::x86_avx512_psrli_d_512:
6366 case Intrinsic::x86_avx512_psrli_q_512:
6367 case Intrinsic::x86_avx512_psrai_w_512:
6368 case Intrinsic::x86_avx512_psrai_d_512:
6369 case Intrinsic::x86_avx512_psrai_q_512:
6370 case Intrinsic::x86_avx512_psra_q_256:
6371 case Intrinsic::x86_avx512_psra_q_128:
6372 case Intrinsic::x86_avx512_psrai_q_256:
6373 case Intrinsic::x86_avx512_psrai_q_128:
6374 case Intrinsic::x86_avx2_psll_w:
6375 case Intrinsic::x86_avx2_psll_d:
6376 case Intrinsic::x86_avx2_psll_q:
6377 case Intrinsic::x86_avx2_pslli_w:
6378 case Intrinsic::x86_avx2_pslli_d:
6379 case Intrinsic::x86_avx2_pslli_q:
6380 case Intrinsic::x86_avx2_psrl_w:
6381 case Intrinsic::x86_avx2_psrl_d:
6382 case Intrinsic::x86_avx2_psrl_q:
6383 case Intrinsic::x86_avx2_psra_w:
6384 case Intrinsic::x86_avx2_psra_d:
6385 case Intrinsic::x86_avx2_psrli_w:
6386 case Intrinsic::x86_avx2_psrli_d:
6387 case Intrinsic::x86_avx2_psrli_q:
6388 case Intrinsic::x86_avx2_psrai_w:
6389 case Intrinsic::x86_avx2_psrai_d:
6390 case Intrinsic::x86_sse2_psll_w:
6391 case Intrinsic::x86_sse2_psll_d:
6392 case Intrinsic::x86_sse2_psll_q:
6393 case Intrinsic::x86_sse2_pslli_w:
6394 case Intrinsic::x86_sse2_pslli_d:
6395 case Intrinsic::x86_sse2_pslli_q:
6396 case Intrinsic::x86_sse2_psrl_w:
6397 case Intrinsic::x86_sse2_psrl_d:
6398 case Intrinsic::x86_sse2_psrl_q:
6399 case Intrinsic::x86_sse2_psra_w:
6400 case Intrinsic::x86_sse2_psra_d:
6401 case Intrinsic::x86_sse2_psrli_w:
6402 case Intrinsic::x86_sse2_psrli_d:
6403 case Intrinsic::x86_sse2_psrli_q:
6404 case Intrinsic::x86_sse2_psrai_w:
6405 case Intrinsic::x86_sse2_psrai_d:
6406 case Intrinsic::x86_mmx_psll_w:
6407 case Intrinsic::x86_mmx_psll_d:
6408 case Intrinsic::x86_mmx_psll_q:
6409 case Intrinsic::x86_mmx_pslli_w:
6410 case Intrinsic::x86_mmx_pslli_d:
6411 case Intrinsic::x86_mmx_pslli_q:
6412 case Intrinsic::x86_mmx_psrl_w:
6413 case Intrinsic::x86_mmx_psrl_d:
6414 case Intrinsic::x86_mmx_psrl_q:
6415 case Intrinsic::x86_mmx_psra_w:
6416 case Intrinsic::x86_mmx_psra_d:
6417 case Intrinsic::x86_mmx_psrli_w:
6418 case Intrinsic::x86_mmx_psrli_d:
6419 case Intrinsic::x86_mmx_psrli_q:
6420 case Intrinsic::x86_mmx_psrai_w:
6421 case Intrinsic::x86_mmx_psrai_d:
6422 handleVectorShiftIntrinsic(I, /* Variable */ false);
6423 break;
6424 case Intrinsic::x86_avx2_psllv_d:
6425 case Intrinsic::x86_avx2_psllv_d_256:
6426 case Intrinsic::x86_avx512_psllv_d_512:
6427 case Intrinsic::x86_avx2_psllv_q:
6428 case Intrinsic::x86_avx2_psllv_q_256:
6429 case Intrinsic::x86_avx512_psllv_q_512:
6430 case Intrinsic::x86_avx2_psrlv_d:
6431 case Intrinsic::x86_avx2_psrlv_d_256:
6432 case Intrinsic::x86_avx512_psrlv_d_512:
6433 case Intrinsic::x86_avx2_psrlv_q:
6434 case Intrinsic::x86_avx2_psrlv_q_256:
6435 case Intrinsic::x86_avx512_psrlv_q_512:
6436 case Intrinsic::x86_avx2_psrav_d:
6437 case Intrinsic::x86_avx2_psrav_d_256:
6438 case Intrinsic::x86_avx512_psrav_d_512:
6439 case Intrinsic::x86_avx512_psrav_q_128:
6440 case Intrinsic::x86_avx512_psrav_q_256:
6441 case Intrinsic::x86_avx512_psrav_q_512:
6442 handleVectorShiftIntrinsic(I, /* Variable */ true);
6443 break;
6444
6445 // Pack with Signed/Unsigned Saturation
6446 case Intrinsic::x86_sse2_packsswb_128:
6447 case Intrinsic::x86_sse2_packssdw_128:
6448 case Intrinsic::x86_sse2_packuswb_128:
6449 case Intrinsic::x86_sse41_packusdw:
6450 case Intrinsic::x86_avx2_packsswb:
6451 case Intrinsic::x86_avx2_packssdw:
6452 case Intrinsic::x86_avx2_packuswb:
6453 case Intrinsic::x86_avx2_packusdw:
6454 // e.g., <64 x i8> @llvm.x86.avx512.packsswb.512
6455 // (<32 x i16> %a, <32 x i16> %b)
6456 // <32 x i16> @llvm.x86.avx512.packssdw.512
6457 // (<16 x i32> %a, <16 x i32> %b)
6458 // Note: AVX512 masked variants are auto-upgraded by LLVM.
6459 case Intrinsic::x86_avx512_packsswb_512:
6460 case Intrinsic::x86_avx512_packssdw_512:
6461 case Intrinsic::x86_avx512_packuswb_512:
6462 case Intrinsic::x86_avx512_packusdw_512:
6463 handleVectorPackIntrinsic(I);
6464 break;
6465
6466 case Intrinsic::x86_sse41_pblendvb:
6467 case Intrinsic::x86_sse41_blendvpd:
6468 case Intrinsic::x86_sse41_blendvps:
6469 case Intrinsic::x86_avx_blendv_pd_256:
6470 case Intrinsic::x86_avx_blendv_ps_256:
6471 case Intrinsic::x86_avx2_pblendvb:
6472 handleBlendvIntrinsic(I);
6473 break;
6474
6475 case Intrinsic::x86_avx_dp_ps_256:
6476 case Intrinsic::x86_sse41_dppd:
6477 case Intrinsic::x86_sse41_dpps:
6478 handleDppIntrinsic(I);
6479 break;
6480
6481 case Intrinsic::x86_mmx_packsswb:
6482 case Intrinsic::x86_mmx_packuswb:
6483 handleVectorPackIntrinsic(I, 16);
6484 break;
6485
6486 case Intrinsic::x86_mmx_packssdw:
6487 handleVectorPackIntrinsic(I, 32);
6488 break;
6489
6490 case Intrinsic::x86_mmx_psad_bw:
6491 handleVectorSadIntrinsic(I, true);
6492 break;
6493 case Intrinsic::x86_sse2_psad_bw:
6494 case Intrinsic::x86_avx2_psad_bw:
6495 handleVectorSadIntrinsic(I);
6496 break;
6497
6498 // Multiply and Add Packed Words
6499 // < 4 x i32> @llvm.x86.sse2.pmadd.wd(<8 x i16>, <8 x i16>)
6500 // < 8 x i32> @llvm.x86.avx2.pmadd.wd(<16 x i16>, <16 x i16>)
6501 // <16 x i32> @llvm.x86.avx512.pmaddw.d.512(<32 x i16>, <32 x i16>)
6502 //
6503 // Multiply and Add Packed Signed and Unsigned Bytes
6504 // < 8 x i16> @llvm.x86.ssse3.pmadd.ub.sw.128(<16 x i8>, <16 x i8>)
6505 // <16 x i16> @llvm.x86.avx2.pmadd.ub.sw(<32 x i8>, <32 x i8>)
6506 // <32 x i16> @llvm.x86.avx512.pmaddubs.w.512(<64 x i8>, <64 x i8>)
6507 //
6508 // These intrinsics are auto-upgraded into non-masked forms:
6509 // < 4 x i32> @llvm.x86.avx512.mask.pmaddw.d.128
6510 // (<8 x i16>, <8 x i16>, <4 x i32>, i8)
6511 // < 8 x i32> @llvm.x86.avx512.mask.pmaddw.d.256
6512 // (<16 x i16>, <16 x i16>, <8 x i32>, i8)
6513 // <16 x i32> @llvm.x86.avx512.mask.pmaddw.d.512
6514 // (<32 x i16>, <32 x i16>, <16 x i32>, i16)
6515 // < 8 x i16> @llvm.x86.avx512.mask.pmaddubs.w.128
6516 // (<16 x i8>, <16 x i8>, <8 x i16>, i8)
6517 // <16 x i16> @llvm.x86.avx512.mask.pmaddubs.w.256
6518 // (<32 x i8>, <32 x i8>, <16 x i16>, i16)
6519 // <32 x i16> @llvm.x86.avx512.mask.pmaddubs.w.512
6520 // (<64 x i8>, <64 x i8>, <32 x i16>, i32)
6521 case Intrinsic::x86_sse2_pmadd_wd:
6522 case Intrinsic::x86_avx2_pmadd_wd:
6523 case Intrinsic::x86_avx512_pmaddw_d_512:
6524 case Intrinsic::x86_ssse3_pmadd_ub_sw_128:
6525 case Intrinsic::x86_avx2_pmadd_ub_sw:
6526 case Intrinsic::x86_avx512_pmaddubs_w_512:
6527 handleVectorDotProductIntrinsic(I, /*ReductionFactor=*/2,
6528 /*ZeroPurifies=*/true,
6529 /*EltSizeInBits=*/0,
6530 /*Lanes=*/kBothLanes);
6531 break;
6532
6533 // <1 x i64> @llvm.x86.ssse3.pmadd.ub.sw(<1 x i64>, <1 x i64>)
6534 case Intrinsic::x86_ssse3_pmadd_ub_sw:
6535 handleVectorDotProductIntrinsic(I, /*ReductionFactor=*/2,
6536 /*ZeroPurifies=*/true,
6537 /*EltSizeInBits=*/8,
6538 /*Lanes=*/kBothLanes);
6539 break;
6540
6541 // <1 x i64> @llvm.x86.mmx.pmadd.wd(<1 x i64>, <1 x i64>)
6542 case Intrinsic::x86_mmx_pmadd_wd:
6543 handleVectorDotProductIntrinsic(I, /*ReductionFactor=*/2,
6544 /*ZeroPurifies=*/true,
6545 /*EltSizeInBits=*/16,
6546 /*Lanes=*/kBothLanes);
6547 break;
6548
6549 // BFloat16 multiply-add to single-precision
6550 // <4 x float> llvm.aarch64.neon.bfmlalt
6551 // (<4 x float>, <8 x bfloat>, <8 x bfloat>)
6552 case Intrinsic::aarch64_neon_bfmlalt:
6553 handleVectorDotProductIntrinsic(I, /*ReductionFactor=*/2,
6554 /*ZeroPurifies=*/false,
6555 /*EltSizeInBits=*/0,
6556 /*Lanes=*/kOddLanes);
6557 break;
6558
6559 // <4 x float> llvm.aarch64.neon.bfmlalb
6560 // (<4 x float>, <8 x bfloat>, <8 x bfloat>)
6561 case Intrinsic::aarch64_neon_bfmlalb:
6562 handleVectorDotProductIntrinsic(I, /*ReductionFactor=*/2,
6563 /*ZeroPurifies=*/false,
6564 /*EltSizeInBits=*/0,
6565 /*Lanes=*/kEvenLanes);
6566 break;
6567
6568 // AVX Vector Neural Network Instructions: bytes
6569 //
6570 // Multiply and Add Signed Bytes
6571 // < 4 x i32> @llvm.x86.avx2.vpdpbssd.128
6572 // (< 4 x i32>, <16 x i8>, <16 x i8>)
6573 // < 8 x i32> @llvm.x86.avx2.vpdpbssd.256
6574 // (< 8 x i32>, <32 x i8>, <32 x i8>)
6575 // <16 x i32> @llvm.x86.avx10.vpdpbssd.512
6576 // (<16 x i32>, <64 x i8>, <64 x i8>)
6577 //
6578 // Multiply and Add Signed Bytes With Saturation
6579 // < 4 x i32> @llvm.x86.avx2.vpdpbssds.128
6580 // (< 4 x i32>, <16 x i8>, <16 x i8>)
6581 // < 8 x i32> @llvm.x86.avx2.vpdpbssds.256
6582 // (< 8 x i32>, <32 x i8>, <32 x i8>)
6583 // <16 x i32> @llvm.x86.avx10.vpdpbssds.512
6584 // (<16 x i32>, <64 x i8>, <64 x i8>)
6585 //
6586 // Multiply and Add Signed and Unsigned Bytes
6587 // < 4 x i32> @llvm.x86.avx2.vpdpbsud.128
6588 // (< 4 x i32>, <16 x i8>, <16 x i8>)
6589 // < 8 x i32> @llvm.x86.avx2.vpdpbsud.256
6590 // (< 8 x i32>, <32 x i8>, <32 x i8>)
6591 // <16 x i32> @llvm.x86.avx10.vpdpbsud.512
6592 // (<16 x i32>, <64 x i8>, <64 x i8>)
6593 //
6594 // Multiply and Add Signed and Unsigned Bytes With Saturation
6595 // < 4 x i32> @llvm.x86.avx2.vpdpbsuds.128
6596 // (< 4 x i32>, <16 x i8>, <16 x i8>)
6597 // < 8 x i32> @llvm.x86.avx2.vpdpbsuds.256
6598 // (< 8 x i32>, <32 x i8>, <32 x i8>)
6599 // <16 x i32> @llvm.x86.avx512.vpdpbusds.512
6600 // (<16 x i32>, <64 x i8>, <64 x i8>)
6601 //
6602 // Multiply and Add Unsigned and Signed Bytes
6603 // < 4 x i32> @llvm.x86.avx512.vpdpbusd.128
6604 // (< 4 x i32>, <16 x i8>, <16 x i8>)
6605 // < 8 x i32> @llvm.x86.avx512.vpdpbusd.256
6606 // (< 8 x i32>, <32 x i8>, <32 x i8>)
6607 // <16 x i32> @llvm.x86.avx512.vpdpbusd.512
6608 // (<16 x i32>, <64 x i8>, <64 x i8>)
6609 //
6610 // Multiply and Add Unsigned and Signed Bytes With Saturation
6611 // < 4 x i32> @llvm.x86.avx512.vpdpbusds.128
6612 // (< 4 x i32>, <16 x i8>, <16 x i8>)
6613 // < 8 x i32> @llvm.x86.avx512.vpdpbusds.256
6614 // (< 8 x i32>, <32 x i8>, <32 x i8>)
6615 // <16 x i32> @llvm.x86.avx10.vpdpbsuds.512
6616 // (<16 x i32>, <64 x i8>, <64 x i8>)
6617 //
6618 // Multiply and Add Unsigned Bytes
6619 // < 4 x i32> @llvm.x86.avx2.vpdpbuud.128
6620 // (< 4 x i32>, <16 x i8>, <16 x i8>)
6621 // < 8 x i32> @llvm.x86.avx2.vpdpbuud.256
6622 // (< 8 x i32>, <32 x i8>, <32 x i8>)
6623 // <16 x i32> @llvm.x86.avx10.vpdpbuud.512
6624 // (<16 x i32>, <64 x i8>, <64 x i8>)
6625 //
6626 // Multiply and Add Unsigned Bytes With Saturation
6627 // < 4 x i32> @llvm.x86.avx2.vpdpbuuds.128
6628 // (< 4 x i32>, <16 x i8>, <16 x i8>)
6629 // < 8 x i32> @llvm.x86.avx2.vpdpbuuds.256
6630 // (< 8 x i32>, <32 x i8>, <32 x i8>)
6631 // <16 x i32> @llvm.x86.avx10.vpdpbuuds.512
6632 // (<16 x i32>, <64 x i8>, <64 x i8>)
6633 //
6634 // These intrinsics are auto-upgraded into non-masked forms:
6635 // <4 x i32> @llvm.x86.avx512.mask.vpdpbusd.128
6636 // (<4 x i32>, <16 x i8>, <16 x i8>, i8)
6637 // <4 x i32> @llvm.x86.avx512.maskz.vpdpbusd.128
6638 // (<4 x i32>, <16 x i8>, <16 x i8>, i8)
6639 // <8 x i32> @llvm.x86.avx512.mask.vpdpbusd.256
6640 // (<8 x i32>, <32 x i8>, <32 x i8>, i8)
6641 // <8 x i32> @llvm.x86.avx512.maskz.vpdpbusd.256
6642 // (<8 x i32>, <32 x i8>, <32 x i8>, i8)
6643 // <16 x i32> @llvm.x86.avx512.mask.vpdpbusd.512
6644 // (<16 x i32>, <64 x i8>, <64 x i8>, i16)
6645 // <16 x i32> @llvm.x86.avx512.maskz.vpdpbusd.512
6646 // (<16 x i32>, <64 x i8>, <64 x i8>, i16)
6647 //
6648 // <4 x i32> @llvm.x86.avx512.mask.vpdpbusds.128
6649 // (<4 x i32>, <16 x i8>, <16 x i8>, i8)
6650 // <4 x i32> @llvm.x86.avx512.maskz.vpdpbusds.128
6651 // (<4 x i32>, <16 x i8>, <16 x i8>, i8)
6652 // <8 x i32> @llvm.x86.avx512.mask.vpdpbusds.256
6653 // (<8 x i32>, <32 x i8>, <32 x i8>, i8)
6654 // <8 x i32> @llvm.x86.avx512.maskz.vpdpbusds.256
6655 // (<8 x i32>, <32 x i8>, <32 x i8>, i8)
6656 // <16 x i32> @llvm.x86.avx512.mask.vpdpbusds.512
6657 // (<16 x i32>, <64 x i8>, <64 x i8>, i16)
6658 // <16 x i32> @llvm.x86.avx512.maskz.vpdpbusds.512
6659 // (<16 x i32>, <64 x i8>, <64 x i8>, i16)
6660 case Intrinsic::x86_avx512_vpdpbusd_128:
6661 case Intrinsic::x86_avx512_vpdpbusd_256:
6662 case Intrinsic::x86_avx512_vpdpbusd_512:
6663 case Intrinsic::x86_avx512_vpdpbusds_128:
6664 case Intrinsic::x86_avx512_vpdpbusds_256:
6665 case Intrinsic::x86_avx512_vpdpbusds_512:
6666 case Intrinsic::x86_avx2_vpdpbssd_128:
6667 case Intrinsic::x86_avx2_vpdpbssd_256:
6668 case Intrinsic::x86_avx10_vpdpbssd_512:
6669 case Intrinsic::x86_avx2_vpdpbssds_128:
6670 case Intrinsic::x86_avx2_vpdpbssds_256:
6671 case Intrinsic::x86_avx10_vpdpbssds_512:
6672 case Intrinsic::x86_avx2_vpdpbsud_128:
6673 case Intrinsic::x86_avx2_vpdpbsud_256:
6674 case Intrinsic::x86_avx10_vpdpbsud_512:
6675 case Intrinsic::x86_avx2_vpdpbsuds_128:
6676 case Intrinsic::x86_avx2_vpdpbsuds_256:
6677 case Intrinsic::x86_avx10_vpdpbsuds_512:
6678 case Intrinsic::x86_avx2_vpdpbuud_128:
6679 case Intrinsic::x86_avx2_vpdpbuud_256:
6680 case Intrinsic::x86_avx10_vpdpbuud_512:
6681 case Intrinsic::x86_avx2_vpdpbuuds_128:
6682 case Intrinsic::x86_avx2_vpdpbuuds_256:
6683 case Intrinsic::x86_avx10_vpdpbuuds_512:
6684 handleVectorDotProductIntrinsic(I, /*ReductionFactor=*/4,
6685 /*ZeroPurifies=*/true,
6686 /*EltSizeInBits=*/0,
6687 /*Lanes=*/kBothLanes);
6688 break;
6689
6690 // AVX Vector Neural Network Instructions: words
6691 //
6692 // Multiply and Add Signed Word Integers
6693 // < 4 x i32> @llvm.x86.avx512.vpdpwssd.128
6694 // (< 4 x i32>, < 8 x i16>, < 8 x i16>)
6695 // < 8 x i32> @llvm.x86.avx512.vpdpwssd.256
6696 // (< 8 x i32>, <16 x i16>, <16 x i16>)
6697 // <16 x i32> @llvm.x86.avx512.vpdpwssd.512
6698 // (<16 x i32>, <32 x i16>, <32 x i16>)
6699 //
6700 // Multiply and Add Signed Word Integers With Saturation
6701 // < 4 x i32> @llvm.x86.avx512.vpdpwssds.128
6702 // (< 4 x i32>, < 8 x i16>, < 8 x i16>)
6703 // < 8 x i32> @llvm.x86.avx512.vpdpwssds.256
6704 // (< 8 x i32>, <16 x i16>, <16 x i16>)
6705 // <16 x i32> @llvm.x86.avx512.vpdpwssds.512
6706 // (<16 x i32>, <32 x i16>, <32 x i16>)
6707 //
6708 // Multiply and Add Signed and Unsigned Word Integers
6709 // < 4 x i32> @llvm.x86.avx2.vpdpwsud.128
6710 // (< 4 x i32>, < 8 x i16>, < 8 x i16>)
6711 // < 8 x i32> @llvm.x86.avx2.vpdpwsud.256
6712 // (< 8 x i32>, <16 x i16>, <16 x i16>)
6713 // <16 x i32> @llvm.x86.avx10.vpdpwsud.512
6714 // (<16 x i32>, <32 x i16>, <32 x i16>)
6715 //
6716 // Multiply and Add Signed and Unsigned Word Integers With Saturation
6717 // < 4 x i32> @llvm.x86.avx2.vpdpwsuds.128
6718 // (< 4 x i32>, < 8 x i16>, < 8 x i16>)
6719 // < 8 x i32> @llvm.x86.avx2.vpdpwsuds.256
6720 // (< 8 x i32>, <16 x i16>, <16 x i16>)
6721 // <16 x i32> @llvm.x86.avx10.vpdpwsuds.512
6722 // (<16 x i32>, <32 x i16>, <32 x i16>)
6723 //
6724 // Multiply and Add Unsigned and Signed Word Integers
6725 // < 4 x i32> @llvm.x86.avx2.vpdpwusd.128
6726 // (< 4 x i32>, < 8 x i16>, < 8 x i16>)
6727 // < 8 x i32> @llvm.x86.avx2.vpdpwusd.256
6728 // (< 8 x i32>, <16 x i16>, <16 x i16>)
6729 // <16 x i32> @llvm.x86.avx10.vpdpwusd.512
6730 // (<16 x i32>, <32 x i16>, <32 x i16>)
6731 //
6732 // Multiply and Add Unsigned and Signed Word Integers With Saturation
6733 // < 4 x i32> @llvm.x86.avx2.vpdpwusds.128
6734 // (< 4 x i32>, < 8 x i16>, < 8 x i16>)
6735 // < 8 x i32> @llvm.x86.avx2.vpdpwusds.256
6736 // (< 8 x i32>, <16 x i16>, <16 x i16>)
6737 // <16 x i32> @llvm.x86.avx10.vpdpwusds.512
6738 // (<16 x i32>, <32 x i16>, <32 x i16>)
6739 //
6740 // Multiply and Add Unsigned and Unsigned Word Integers
6741 // < 4 x i32> @llvm.x86.avx2.vpdpwuud.128
6742 // (< 4 x i32>, < 8 x i16>, < 8 x i16>)
6743 // < 8 x i32> @llvm.x86.avx2.vpdpwuud.256
6744 // (< 8 x i32>, <16 x i16>, <16 x i16>)
6745 // <16 x i32> @llvm.x86.avx10.vpdpwuud.512
6746 // (<16 x i32>, <32 x i16>, <32 x i16>)
6747 //
6748 // Multiply and Add Unsigned and Unsigned Word Integers With Saturation
6749 // < 4 x i32> @llvm.x86.avx2.vpdpwuuds.128
6750 // (< 4 x i32>, < 8 x i16>, < 8 x i16>)
6751 // < 8 x i32> @llvm.x86.avx2.vpdpwuuds.256
6752 // (< 8 x i32>, <16 x i16>, <16 x i16>)
6753 // <16 x i32> @llvm.x86.avx10.vpdpwuuds.512
6754 // (<16 x i32>, <32 x i16>, <32 x i16>)
6755 //
6756 // These intrinsics are auto-upgraded into non-masked forms:
6757 // <4 x i32> @llvm.x86.avx512.mask.vpdpwssd.128
6758 // (<4 x i32>, <8 x i16>, <8 x i16>, i8)
6759 // <4 x i32> @llvm.x86.avx512.maskz.vpdpwssd.128
6760 // (<4 x i32>, <8 x i16>, <8 x i16>, i8)
6761 // <8 x i32> @llvm.x86.avx512.mask.vpdpwssd.256
6762 // (<8 x i32>, <16 x i16>, <16 x i16>, i8)
6763 // <8 x i32> @llvm.x86.avx512.maskz.vpdpwssd.256
6764 // (<8 x i32>, <16 x i16>, <16 x i16>, i8)
6765 // <16 x i32> @llvm.x86.avx512.mask.vpdpwssd.512
6766 // (<16 x i32>, <32 x i16>, <32 x i16>, i16)
6767 // <16 x i32> @llvm.x86.avx512.maskz.vpdpwssd.512
6768 // (<16 x i32>, <32 x i16>, <32 x i16>, i16)
6769 //
6770 // <4 x i32> @llvm.x86.avx512.mask.vpdpwssds.128
6771 // (<4 x i32>, <8 x i16>, <8 x i16>, i8)
6772 // <4 x i32> @llvm.x86.avx512.maskz.vpdpwssds.128
6773 // (<4 x i32>, <8 x i16>, <8 x i16>, i8)
6774 // <8 x i32> @llvm.x86.avx512.mask.vpdpwssds.256
6775 // (<8 x i32>, <16 x i16>, <16 x i16>, i8)
6776 // <8 x i32> @llvm.x86.avx512.maskz.vpdpwssds.256
6777 // (<8 x i32>, <16 x i16>, <16 x i16>, i8)
6778 // <16 x i32> @llvm.x86.avx512.mask.vpdpwssds.512
6779 // (<16 x i32>, <32 x i16>, <32 x i16>, i16)
6780 // <16 x i32> @llvm.x86.avx512.maskz.vpdpwssds.512
6781 // (<16 x i32>, <32 x i16>, <32 x i16>, i16)
6782 case Intrinsic::x86_avx512_vpdpwssd_128:
6783 case Intrinsic::x86_avx512_vpdpwssd_256:
6784 case Intrinsic::x86_avx512_vpdpwssd_512:
6785 case Intrinsic::x86_avx512_vpdpwssds_128:
6786 case Intrinsic::x86_avx512_vpdpwssds_256:
6787 case Intrinsic::x86_avx512_vpdpwssds_512:
6788 case Intrinsic::x86_avx2_vpdpwsud_128:
6789 case Intrinsic::x86_avx2_vpdpwsud_256:
6790 case Intrinsic::x86_avx10_vpdpwsud_512:
6791 case Intrinsic::x86_avx2_vpdpwsuds_128:
6792 case Intrinsic::x86_avx2_vpdpwsuds_256:
6793 case Intrinsic::x86_avx10_vpdpwsuds_512:
6794 case Intrinsic::x86_avx2_vpdpwusd_128:
6795 case Intrinsic::x86_avx2_vpdpwusd_256:
6796 case Intrinsic::x86_avx10_vpdpwusd_512:
6797 case Intrinsic::x86_avx2_vpdpwusds_128:
6798 case Intrinsic::x86_avx2_vpdpwusds_256:
6799 case Intrinsic::x86_avx10_vpdpwusds_512:
6800 case Intrinsic::x86_avx2_vpdpwuud_128:
6801 case Intrinsic::x86_avx2_vpdpwuud_256:
6802 case Intrinsic::x86_avx10_vpdpwuud_512:
6803 case Intrinsic::x86_avx2_vpdpwuuds_128:
6804 case Intrinsic::x86_avx2_vpdpwuuds_256:
6805 case Intrinsic::x86_avx10_vpdpwuuds_512:
6806 handleVectorDotProductIntrinsic(I, /*ReductionFactor=*/2,
6807 /*ZeroPurifies=*/true,
6808 /*EltSizeInBits=*/0,
6809 /*Lanes=*/kBothLanes);
6810 break;
6811
6812 // Dot Product of BF16 Pairs Accumulated Into Packed Single
6813 // Precision
6814 // <4 x float> @llvm.x86.avx512bf16.dpbf16ps.128
6815 // (<4 x float>, <8 x bfloat>, <8 x bfloat>)
6816 // <8 x float> @llvm.x86.avx512bf16.dpbf16ps.256
6817 // (<8 x float>, <16 x bfloat>, <16 x bfloat>)
6818 // <16 x float> @llvm.x86.avx512bf16.dpbf16ps.512
6819 // (<16 x float>, <32 x bfloat>, <32 x bfloat>)
6820 case Intrinsic::x86_avx512bf16_dpbf16ps_128:
6821 case Intrinsic::x86_avx512bf16_dpbf16ps_256:
6822 case Intrinsic::x86_avx512bf16_dpbf16ps_512:
6823 handleVectorDotProductIntrinsic(I, /*ReductionFactor=*/2,
6824 /*ZeroPurifies=*/false,
6825 /*EltSizeInBits=*/0,
6826 /*Lanes=*/kBothLanes);
6827 break;
6828
6829 case Intrinsic::x86_sse_cmp_ss:
6830 case Intrinsic::x86_sse2_cmp_sd:
6831 case Intrinsic::x86_sse_comieq_ss:
6832 case Intrinsic::x86_sse_comilt_ss:
6833 case Intrinsic::x86_sse_comile_ss:
6834 case Intrinsic::x86_sse_comigt_ss:
6835 case Intrinsic::x86_sse_comige_ss:
6836 case Intrinsic::x86_sse_comineq_ss:
6837 case Intrinsic::x86_sse_ucomieq_ss:
6838 case Intrinsic::x86_sse_ucomilt_ss:
6839 case Intrinsic::x86_sse_ucomile_ss:
6840 case Intrinsic::x86_sse_ucomigt_ss:
6841 case Intrinsic::x86_sse_ucomige_ss:
6842 case Intrinsic::x86_sse_ucomineq_ss:
6843 case Intrinsic::x86_sse2_comieq_sd:
6844 case Intrinsic::x86_sse2_comilt_sd:
6845 case Intrinsic::x86_sse2_comile_sd:
6846 case Intrinsic::x86_sse2_comigt_sd:
6847 case Intrinsic::x86_sse2_comige_sd:
6848 case Intrinsic::x86_sse2_comineq_sd:
6849 case Intrinsic::x86_sse2_ucomieq_sd:
6850 case Intrinsic::x86_sse2_ucomilt_sd:
6851 case Intrinsic::x86_sse2_ucomile_sd:
6852 case Intrinsic::x86_sse2_ucomigt_sd:
6853 case Intrinsic::x86_sse2_ucomige_sd:
6854 case Intrinsic::x86_sse2_ucomineq_sd:
6855 handleVectorCompareScalarIntrinsic(I);
6856 break;
6857
6858 case Intrinsic::x86_avx_cmp_pd_256:
6859 case Intrinsic::x86_avx_cmp_ps_256:
6860 case Intrinsic::x86_sse2_cmp_pd:
6861 case Intrinsic::x86_sse_cmp_ps:
6862 handleVectorComparePackedIntrinsic(I, /*PredicateAsOperand=*/true);
6863 break;
6864
6865 case Intrinsic::x86_bmi_bextr_32:
6866 case Intrinsic::x86_bmi_bextr_64:
6867 case Intrinsic::x86_bmi_bzhi_32:
6868 case Intrinsic::x86_bmi_bzhi_64:
6869 handleGenericBitManipulation(I);
6870 break;
6871
6872 case Intrinsic::x86_pclmulqdq:
6873 case Intrinsic::x86_pclmulqdq_256:
6874 case Intrinsic::x86_pclmulqdq_512:
6875 handlePclmulIntrinsic(I);
6876 break;
6877
6878 case Intrinsic::x86_avx_round_pd_256:
6879 case Intrinsic::x86_avx_round_ps_256:
6880 case Intrinsic::x86_sse41_round_pd:
6881 case Intrinsic::x86_sse41_round_ps:
6882 handleRoundPdPsIntrinsic(I);
6883 break;
6884
6885 case Intrinsic::x86_sse41_round_sd:
6886 case Intrinsic::x86_sse41_round_ss:
6887 handleUnarySdSsIntrinsic(I);
6888 break;
6889
6890 case Intrinsic::x86_sse2_max_sd:
6891 case Intrinsic::x86_sse_max_ss:
6892 case Intrinsic::x86_sse2_min_sd:
6893 case Intrinsic::x86_sse_min_ss:
6894 handleBinarySdSsIntrinsic(I);
6895 break;
6896
6897 case Intrinsic::x86_avx_vtestc_pd:
6898 case Intrinsic::x86_avx_vtestc_pd_256:
6899 case Intrinsic::x86_avx_vtestc_ps:
6900 case Intrinsic::x86_avx_vtestc_ps_256:
6901 case Intrinsic::x86_avx_vtestnzc_pd:
6902 case Intrinsic::x86_avx_vtestnzc_pd_256:
6903 case Intrinsic::x86_avx_vtestnzc_ps:
6904 case Intrinsic::x86_avx_vtestnzc_ps_256:
6905 case Intrinsic::x86_avx_vtestz_pd:
6906 case Intrinsic::x86_avx_vtestz_pd_256:
6907 case Intrinsic::x86_avx_vtestz_ps:
6908 case Intrinsic::x86_avx_vtestz_ps_256:
6909 case Intrinsic::x86_avx_ptestc_256:
6910 case Intrinsic::x86_avx_ptestnzc_256:
6911 case Intrinsic::x86_avx_ptestz_256:
6912 case Intrinsic::x86_sse41_ptestc:
6913 case Intrinsic::x86_sse41_ptestnzc:
6914 case Intrinsic::x86_sse41_ptestz:
6915 handleVtestIntrinsic(I);
6916 break;
6917
6918 // Packed Horizontal Add/Subtract
6919 case Intrinsic::x86_ssse3_phadd_w:
6920 case Intrinsic::x86_ssse3_phadd_w_128:
6921 case Intrinsic::x86_ssse3_phsub_w:
6922 case Intrinsic::x86_ssse3_phsub_w_128:
6923 handlePairwiseShadowOrIntrinsic(I, /*Shards=*/1,
6924 /*ReinterpretElemWidth=*/16);
6925 break;
6926
6927 case Intrinsic::x86_avx2_phadd_w:
6928 case Intrinsic::x86_avx2_phsub_w:
6929 handlePairwiseShadowOrIntrinsic(I, /*Shards=*/2,
6930 /*ReinterpretElemWidth=*/16);
6931 break;
6932
6933 // Packed Horizontal Add/Subtract
6934 case Intrinsic::x86_ssse3_phadd_d:
6935 case Intrinsic::x86_ssse3_phadd_d_128:
6936 case Intrinsic::x86_ssse3_phsub_d:
6937 case Intrinsic::x86_ssse3_phsub_d_128:
6938 handlePairwiseShadowOrIntrinsic(I, /*Shards=*/1,
6939 /*ReinterpretElemWidth=*/32);
6940 break;
6941
6942 case Intrinsic::x86_avx2_phadd_d:
6943 case Intrinsic::x86_avx2_phsub_d:
6944 handlePairwiseShadowOrIntrinsic(I, /*Shards=*/2,
6945 /*ReinterpretElemWidth=*/32);
6946 break;
6947
6948 // Packed Horizontal Add/Subtract and Saturate
6949 case Intrinsic::x86_ssse3_phadd_sw:
6950 case Intrinsic::x86_ssse3_phadd_sw_128:
6951 case Intrinsic::x86_ssse3_phsub_sw:
6952 case Intrinsic::x86_ssse3_phsub_sw_128:
6953 handlePairwiseShadowOrIntrinsic(I, /*Shards=*/1,
6954 /*ReinterpretElemWidth=*/16);
6955 break;
6956
6957 case Intrinsic::x86_avx2_phadd_sw:
6958 case Intrinsic::x86_avx2_phsub_sw:
6959 handlePairwiseShadowOrIntrinsic(I, /*Shards=*/2,
6960 /*ReinterpretElemWidth=*/16);
6961 break;
6962
6963 // Packed Single/Double Precision Floating-Point Horizontal Add
6964 case Intrinsic::x86_sse3_hadd_ps:
6965 case Intrinsic::x86_sse3_hadd_pd:
6966 case Intrinsic::x86_sse3_hsub_ps:
6967 case Intrinsic::x86_sse3_hsub_pd:
6968 handlePairwiseShadowOrIntrinsic(I, /*Shards=*/1);
6969 break;
6970
6971 case Intrinsic::x86_avx_hadd_pd_256:
6972 case Intrinsic::x86_avx_hadd_ps_256:
6973 case Intrinsic::x86_avx_hsub_pd_256:
6974 case Intrinsic::x86_avx_hsub_ps_256:
6975 handlePairwiseShadowOrIntrinsic(I, /*Shards=*/2);
6976 break;
6977
6978 case Intrinsic::x86_avx_maskstore_ps:
6979 case Intrinsic::x86_avx_maskstore_pd:
6980 case Intrinsic::x86_avx_maskstore_ps_256:
6981 case Intrinsic::x86_avx_maskstore_pd_256:
6982 case Intrinsic::x86_avx2_maskstore_d:
6983 case Intrinsic::x86_avx2_maskstore_q:
6984 case Intrinsic::x86_avx2_maskstore_d_256:
6985 case Intrinsic::x86_avx2_maskstore_q_256: {
6986 handleAVXMaskedStore(I);
6987 break;
6988 }
6989
6990 case Intrinsic::x86_avx_maskload_ps:
6991 case Intrinsic::x86_avx_maskload_pd:
6992 case Intrinsic::x86_avx_maskload_ps_256:
6993 case Intrinsic::x86_avx_maskload_pd_256:
6994 case Intrinsic::x86_avx2_maskload_d:
6995 case Intrinsic::x86_avx2_maskload_q:
6996 case Intrinsic::x86_avx2_maskload_d_256:
6997 case Intrinsic::x86_avx2_maskload_q_256: {
6998 handleAVXMaskedLoad(I);
6999 break;
7000 }
7001
7002 // Packed
7003 case Intrinsic::x86_avx512fp16_add_ph_512:
7004 case Intrinsic::x86_avx512fp16_sub_ph_512:
7005 case Intrinsic::x86_avx512fp16_mul_ph_512:
7006 case Intrinsic::x86_avx512fp16_div_ph_512:
7007 case Intrinsic::x86_avx512fp16_max_ph_512:
7008 case Intrinsic::x86_avx512fp16_min_ph_512:
7009 case Intrinsic::x86_avx512_min_ps_512:
7010 case Intrinsic::x86_avx512_min_pd_512:
7011 case Intrinsic::x86_avx512_max_ps_512:
7012 case Intrinsic::x86_avx512_max_pd_512: {
7013 // These AVX512 variants contain the rounding mode as a trailing flag.
7014 // Earlier variants do not have a trailing flag and are already handled
7015 // by maybeHandleSimpleNomemIntrinsic(I, 0) via
7016 // maybeHandleUnknownIntrinsic.
7017 [[maybe_unused]] bool Success =
7018 maybeHandleSimpleNomemIntrinsic(I, /*trailingFlags=*/1);
7019 assert(Success);
7020 break;
7021 }
7022
7023 case Intrinsic::x86_avx_vpermilvar_pd:
7024 case Intrinsic::x86_avx_vpermilvar_pd_256:
7025 case Intrinsic::x86_avx512_vpermilvar_pd_512:
7026 case Intrinsic::x86_avx_vpermilvar_ps:
7027 case Intrinsic::x86_avx_vpermilvar_ps_256:
7028 case Intrinsic::x86_avx512_vpermilvar_ps_512: {
7029 handleAVXVpermilvar(I);
7030 break;
7031 }
7032
7033 case Intrinsic::x86_avx512_vpermi2var_d_128:
7034 case Intrinsic::x86_avx512_vpermi2var_d_256:
7035 case Intrinsic::x86_avx512_vpermi2var_d_512:
7036 case Intrinsic::x86_avx512_vpermi2var_hi_128:
7037 case Intrinsic::x86_avx512_vpermi2var_hi_256:
7038 case Intrinsic::x86_avx512_vpermi2var_hi_512:
7039 case Intrinsic::x86_avx512_vpermi2var_pd_128:
7040 case Intrinsic::x86_avx512_vpermi2var_pd_256:
7041 case Intrinsic::x86_avx512_vpermi2var_pd_512:
7042 case Intrinsic::x86_avx512_vpermi2var_ps_128:
7043 case Intrinsic::x86_avx512_vpermi2var_ps_256:
7044 case Intrinsic::x86_avx512_vpermi2var_ps_512:
7045 case Intrinsic::x86_avx512_vpermi2var_q_128:
7046 case Intrinsic::x86_avx512_vpermi2var_q_256:
7047 case Intrinsic::x86_avx512_vpermi2var_q_512:
7048 case Intrinsic::x86_avx512_vpermi2var_qi_128:
7049 case Intrinsic::x86_avx512_vpermi2var_qi_256:
7050 case Intrinsic::x86_avx512_vpermi2var_qi_512:
7051 handleAVXVpermi2var(I);
7052 break;
7053
7054 // Packed Shuffle
7055 // llvm.x86.sse.pshuf.w(<1 x i64>, i8)
7056 // llvm.x86.ssse3.pshuf.b(<1 x i64>, <1 x i64>)
7057 // llvm.x86.ssse3.pshuf.b.128(<16 x i8>, <16 x i8>)
7058 // llvm.x86.avx2.pshuf.b(<32 x i8>, <32 x i8>)
7059 // llvm.x86.avx512.pshuf.b.512(<64 x i8>, <64 x i8>)
7060 //
7061 // The following intrinsics are auto-upgraded:
7062 // llvm.x86.sse2.pshuf.d(<4 x i32>, i8)
7063 // llvm.x86.sse2.gpshufh.w(<8 x i16>, i8)
7064 // llvm.x86.sse2.pshufl.w(<8 x i16>, i8)
7065 case Intrinsic::x86_avx2_pshuf_b:
7066 case Intrinsic::x86_sse_pshuf_w:
7067 case Intrinsic::x86_ssse3_pshuf_b_128:
7068 case Intrinsic::x86_ssse3_pshuf_b:
7069 case Intrinsic::x86_avx512_pshuf_b_512:
7070 handleIntrinsicByApplyingToShadow(I, I.getIntrinsicID(),
7071 /*verbatimArgsIndices=*/{-1},
7072 /*forceIntegerIntrinsic=*/false);
7073 break;
7074
7075 // AVX512 PMOV: Packed MOV, with truncation
7076 // Precisely handled by applying the same intrinsic to the shadow
7077 case Intrinsic::x86_avx512_mask_pmov_dw_128:
7078 case Intrinsic::x86_avx512_mask_pmov_db_128:
7079 case Intrinsic::x86_avx512_mask_pmov_qb_128:
7080 case Intrinsic::x86_avx512_mask_pmov_qw_128:
7081 case Intrinsic::x86_avx512_mask_pmov_qd_128:
7082 case Intrinsic::x86_avx512_mask_pmov_wb_128:
7083 case Intrinsic::x86_avx512_mask_pmov_dw_256:
7084 case Intrinsic::x86_avx512_mask_pmov_db_256:
7085 case Intrinsic::x86_avx512_mask_pmov_qb_256:
7086 case Intrinsic::x86_avx512_mask_pmov_qw_256:
7087 case Intrinsic::x86_avx512_mask_pmov_dw_512:
7088 case Intrinsic::x86_avx512_mask_pmov_db_512:
7089 case Intrinsic::x86_avx512_mask_pmov_qb_512:
7090 case Intrinsic::x86_avx512_mask_pmov_qw_512: {
7091 // Intrinsic::x86_avx512_mask_pmov_{qd,wb}_{256,512} were removed in
7092 // f608dc1f5775ee880e8ea30e2d06ab5a4a935c22
7093 handleIntrinsicByApplyingToShadow(I, I.getIntrinsicID(),
7094 /*verbatimArgIndices=*/{-1},
7095 /*forceIntegerIntrinsic=*/false);
7096 break;
7097 }
7098
7099 // AVX512 PMOV{S,US}: Packed MOV, with signed/unsigned saturation
7100 // Approximately handled using the corresponding truncation intrinsic
7101 // TODO: improve handleAVX512VectorDownConvert to precisely model saturation
7102 case Intrinsic::x86_avx512_mask_pmovs_dw_512:
7103 case Intrinsic::x86_avx512_mask_pmovus_dw_512: {
7104 handleIntrinsicByApplyingToShadow(
7105 I, Intrinsic::x86_avx512_mask_pmov_dw_512,
7106 /*verbatimArgIndices=*/{-1}, /*forceIntegerIntrinsic=*/false);
7107 break;
7108 }
7109
7110 case Intrinsic::x86_avx512_mask_pmovs_dw_256:
7111 case Intrinsic::x86_avx512_mask_pmovus_dw_256:
7112 handleIntrinsicByApplyingToShadow(
7113 I, Intrinsic::x86_avx512_mask_pmov_dw_256,
7114 /*verbatimArgIndices=*/{-1}, /*forceIntegerIntrinsic=*/false);
7115 break;
7116
7117 case Intrinsic::x86_avx512_mask_pmovs_dw_128:
7118 case Intrinsic::x86_avx512_mask_pmovus_dw_128:
7119 handleIntrinsicByApplyingToShadow(
7120 I, Intrinsic::x86_avx512_mask_pmov_dw_128,
7121 /*verbatimArgIndices=*/{-1}, /*forceIntegerIntrinsic=*/false);
7122 break;
7123
7124 case Intrinsic::x86_avx512_mask_pmovs_db_512:
7125 case Intrinsic::x86_avx512_mask_pmovus_db_512: {
7126 handleIntrinsicByApplyingToShadow(
7127 I, Intrinsic::x86_avx512_mask_pmov_db_512,
7128 /*verbatimArgIndices=*/{-1}, /*forceIntegerIntrinsic=*/false);
7129 break;
7130 }
7131
7132 case Intrinsic::x86_avx512_mask_pmovs_db_256:
7133 case Intrinsic::x86_avx512_mask_pmovus_db_256:
7134 handleIntrinsicByApplyingToShadow(
7135 I, Intrinsic::x86_avx512_mask_pmov_db_256,
7136 /*verbatimArgIndices=*/{-1}, /*forceIntegerIntrinsic=*/false);
7137 break;
7138
7139 case Intrinsic::x86_avx512_mask_pmovs_db_128:
7140 case Intrinsic::x86_avx512_mask_pmovus_db_128:
7141 handleIntrinsicByApplyingToShadow(
7142 I, Intrinsic::x86_avx512_mask_pmov_db_128,
7143 /*verbatimArgIndices=*/{-1}, /*forceIntegerIntrinsic=*/false);
7144 break;
7145
7146 case Intrinsic::x86_avx512_mask_pmovs_qb_512:
7147 case Intrinsic::x86_avx512_mask_pmovus_qb_512: {
7148 handleIntrinsicByApplyingToShadow(
7149 I, Intrinsic::x86_avx512_mask_pmov_qb_512,
7150 /*verbatimArgIndices=*/{-1}, /*forceIntegerIntrinsic=*/false);
7151 break;
7152 }
7153
7154 case Intrinsic::x86_avx512_mask_pmovs_qb_256:
7155 case Intrinsic::x86_avx512_mask_pmovus_qb_256:
7156 handleIntrinsicByApplyingToShadow(
7157 I, Intrinsic::x86_avx512_mask_pmov_qb_256,
7158 /*verbatimArgIndices=*/{-1}, /*forceIntegerIntrinsic=*/false);
7159 break;
7160
7161 case Intrinsic::x86_avx512_mask_pmovs_qb_128:
7162 case Intrinsic::x86_avx512_mask_pmovus_qb_128:
7163 handleIntrinsicByApplyingToShadow(
7164 I, Intrinsic::x86_avx512_mask_pmov_qb_128,
7165 /*verbatimArgIndices=*/{-1}, /*forceIntegerIntrinsic=*/false);
7166 break;
7167
7168 case Intrinsic::x86_avx512_mask_pmovs_qw_512:
7169 case Intrinsic::x86_avx512_mask_pmovus_qw_512: {
7170 handleIntrinsicByApplyingToShadow(
7171 I, Intrinsic::x86_avx512_mask_pmov_qw_512,
7172 /*verbatimArgIndices=*/{-1}, /*forceIntegerIntrinsic=*/false);
7173 break;
7174 }
7175
7176 case Intrinsic::x86_avx512_mask_pmovs_qw_256:
7177 case Intrinsic::x86_avx512_mask_pmovus_qw_256:
7178 handleIntrinsicByApplyingToShadow(
7179 I, Intrinsic::x86_avx512_mask_pmov_qw_256,
7180 /*verbatimArgIndices=*/{-1}, /*forceIntegerIntrinsic=*/false);
7181 break;
7182
7183 case Intrinsic::x86_avx512_mask_pmovs_qw_128:
7184 case Intrinsic::x86_avx512_mask_pmovus_qw_128:
7185 handleIntrinsicByApplyingToShadow(
7186 I, Intrinsic::x86_avx512_mask_pmov_qw_128,
7187 /*verbatimArgIndices=*/{-1}, /*forceIntegerIntrinsic=*/false);
7188 break;
7189
7190 case Intrinsic::x86_avx512_mask_pmovs_qd_128:
7191 case Intrinsic::x86_avx512_mask_pmovus_qd_128:
7192 handleIntrinsicByApplyingToShadow(
7193 I, Intrinsic::x86_avx512_mask_pmov_qd_128,
7194 /*verbatimArgIndices=*/{-1}, /*forceIntegerIntrinsic=*/false);
7195 break;
7196
7197 case Intrinsic::x86_avx512_mask_pmovs_wb_128:
7198 case Intrinsic::x86_avx512_mask_pmovus_wb_128:
7199 handleIntrinsicByApplyingToShadow(
7200 I, Intrinsic::x86_avx512_mask_pmov_wb_128,
7201 /*verbatimArgIndices=*/{-1}, /*forceIntegerIntrinsic=*/false);
7202 break;
7203
7204 case Intrinsic::x86_avx512_mask_pmovs_qd_256:
7205 case Intrinsic::x86_avx512_mask_pmovus_qd_256:
7206 case Intrinsic::x86_avx512_mask_pmovs_wb_256:
7207 case Intrinsic::x86_avx512_mask_pmovus_wb_256:
7208 case Intrinsic::x86_avx512_mask_pmovs_qd_512:
7209 case Intrinsic::x86_avx512_mask_pmovus_qd_512:
7210 case Intrinsic::x86_avx512_mask_pmovs_wb_512:
7211 case Intrinsic::x86_avx512_mask_pmovus_wb_512: {
7212 // Since Intrinsic::x86_avx512_mask_pmov_{qd,wb}_{256,512} do not exist,
7213 // we cannot use handleIntrinsicByApplyingToShadow. Instead, we call the
7214 // slow-path handler.
7215 handleAVX512VectorDownConvert(I);
7216 break;
7217 }
7218
7219 // e.g.,
7220 // <16 x float> @llvm.x86.avx512.mask.compress
7221 // (<16 x float> %data, <16 x float> %passthru,
7222 // <16 x i1> %mask)
7223 // <16 x i32> @llvm.x86.avx512.mask.compress
7224 // (<16 x i32> %data, <16 x i32> %passthru,
7225 // <16 x i1> %mask)
7226 case Intrinsic::x86_avx512_mask_compress:
7227 handleIntrinsicByApplyingToShadow(I, I.getIntrinsicID(),
7228 /*verbatimArgIndices=*/{-1},
7229 /*forceIntegerIntrinsic=*/true);
7230 break;
7231
7232 // AVX512/AVX10 Reciprocal
7233 // <16 x float> @llvm.x86.avx512.rsqrt14.ps.512
7234 // (<16 x float>, <16 x float>, i16)
7235 // <8 x float> @llvm.x86.avx512.rsqrt14.ps.256
7236 // (<8 x float>, <8 x float>, i8)
7237 // <4 x float> @llvm.x86.avx512.rsqrt14.ps.128
7238 // (<4 x float>, <4 x float>, i8)
7239 //
7240 // <8 x double> @llvm.x86.avx512.rsqrt14.pd.512
7241 // (<8 x double>, <8 x double>, i8)
7242 // <4 x double> @llvm.x86.avx512.rsqrt14.pd.256
7243 // (<4 x double>, <4 x double>, i8)
7244 // <2 x double> @llvm.x86.avx512.rsqrt14.pd.128
7245 // (<2 x double>, <2 x double>, i8)
7246 //
7247 // <32 x bfloat> @llvm.x86.avx10.mask.rsqrt.bf16.512
7248 // (<32 x bfloat>, <32 x bfloat>, i32)
7249 // <16 x bfloat> @llvm.x86.avx10.mask.rsqrt.bf16.256
7250 // (<16 x bfloat>, <16 x bfloat>, i16)
7251 // <8 x bfloat> @llvm.x86.avx10.mask.rsqrt.bf16.128
7252 // (<8 x bfloat>, <8 x bfloat>, i8)
7253 //
7254 // <32 x half> @llvm.x86.avx512fp16.mask.rsqrt.ph.512
7255 // (<32 x half>, <32 x half>, i32)
7256 // <16 x half> @llvm.x86.avx512fp16.mask.rsqrt.ph.256
7257 // (<16 x half>, <16 x half>, i16)
7258 // <8 x half> @llvm.x86.avx512fp16.mask.rsqrt.ph.128
7259 // (<8 x half>, <8 x half>, i8)
7260 //
7261 // TODO: 3-operand variants are not handled:
7262 // <2 x double> @llvm.x86.avx512.rsqrt14.sd
7263 // (<2 x double>, <2 x double>, <2 x double>, i8)
7264 // <4 x float> @llvm.x86.avx512.rsqrt14.ss
7265 // (<4 x float>, <4 x float>, <4 x float>, i8)
7266 // <8 x half> @llvm.x86.avx512fp16.mask.rsqrt.sh
7267 // (<8 x half>, <8 x half>, <8 x half>, i8)
7268 case Intrinsic::x86_avx512_rsqrt14_ps_512:
7269 case Intrinsic::x86_avx512_rsqrt14_ps_256:
7270 case Intrinsic::x86_avx512_rsqrt14_ps_128:
7271 case Intrinsic::x86_avx512_rsqrt14_pd_512:
7272 case Intrinsic::x86_avx512_rsqrt14_pd_256:
7273 case Intrinsic::x86_avx512_rsqrt14_pd_128:
7274 case Intrinsic::x86_avx10_mask_rsqrt_bf16_512:
7275 case Intrinsic::x86_avx10_mask_rsqrt_bf16_256:
7276 case Intrinsic::x86_avx10_mask_rsqrt_bf16_128:
7277 case Intrinsic::x86_avx512fp16_mask_rsqrt_ph_512:
7278 case Intrinsic::x86_avx512fp16_mask_rsqrt_ph_256:
7279 case Intrinsic::x86_avx512fp16_mask_rsqrt_ph_128:
7280 handleAVX512VectorGenericMaskedFP(I, /*DataIndices=*/{0},
7281 /*WriteThruIndex=*/1,
7282 /*MaskIndex=*/2);
7283 break;
7284
7285 // AVX512/AVX10 Reciprocal Square Root
7286 // <16 x float> @llvm.x86.avx512.rcp14.ps.512
7287 // (<16 x float>, <16 x float>, i16)
7288 // <8 x float> @llvm.x86.avx512.rcp14.ps.256
7289 // (<8 x float>, <8 x float>, i8)
7290 // <4 x float> @llvm.x86.avx512.rcp14.ps.128
7291 // (<4 x float>, <4 x float>, i8)
7292 //
7293 // <8 x double> @llvm.x86.avx512.rcp14.pd.512
7294 // (<8 x double>, <8 x double>, i8)
7295 // <4 x double> @llvm.x86.avx512.rcp14.pd.256
7296 // (<4 x double>, <4 x double>, i8)
7297 // <2 x double> @llvm.x86.avx512.rcp14.pd.128
7298 // (<2 x double>, <2 x double>, i8)
7299 //
7300 // <32 x bfloat> @llvm.x86.avx10.mask.rcp.bf16.512
7301 // (<32 x bfloat>, <32 x bfloat>, i32)
7302 // <16 x bfloat> @llvm.x86.avx10.mask.rcp.bf16.256
7303 // (<16 x bfloat>, <16 x bfloat>, i16)
7304 // <8 x bfloat> @llvm.x86.avx10.mask.rcp.bf16.128
7305 // (<8 x bfloat>, <8 x bfloat>, i8)
7306 //
7307 // <32 x half> @llvm.x86.avx512fp16.mask.rcp.ph.512
7308 // (<32 x half>, <32 x half>, i32)
7309 // <16 x half> @llvm.x86.avx512fp16.mask.rcp.ph.256
7310 // (<16 x half>, <16 x half>, i16)
7311 // <8 x half> @llvm.x86.avx512fp16.mask.rcp.ph.128
7312 // (<8 x half>, <8 x half>, i8)
7313 //
7314 // TODO: 3-operand variants are not handled:
7315 // <2 x double> @llvm.x86.avx512.rcp14.sd
7316 // (<2 x double>, <2 x double>, <2 x double>, i8)
7317 // <4 x float> @llvm.x86.avx512.rcp14.ss
7318 // (<4 x float>, <4 x float>, <4 x float>, i8)
7319 // <8 x half> @llvm.x86.avx512fp16.mask.rcp.sh
7320 // (<8 x half>, <8 x half>, <8 x half>, i8)
7321 case Intrinsic::x86_avx512_rcp14_ps_512:
7322 case Intrinsic::x86_avx512_rcp14_ps_256:
7323 case Intrinsic::x86_avx512_rcp14_ps_128:
7324 case Intrinsic::x86_avx512_rcp14_pd_512:
7325 case Intrinsic::x86_avx512_rcp14_pd_256:
7326 case Intrinsic::x86_avx512_rcp14_pd_128:
7327 case Intrinsic::x86_avx10_mask_rcp_bf16_512:
7328 case Intrinsic::x86_avx10_mask_rcp_bf16_256:
7329 case Intrinsic::x86_avx10_mask_rcp_bf16_128:
7330 case Intrinsic::x86_avx512fp16_mask_rcp_ph_512:
7331 case Intrinsic::x86_avx512fp16_mask_rcp_ph_256:
7332 case Intrinsic::x86_avx512fp16_mask_rcp_ph_128:
7333 handleAVX512VectorGenericMaskedFP(I, /*DataIndices=*/{0},
7334 /*WriteThruIndex=*/1,
7335 /*MaskIndex=*/2);
7336 break;
7337
7338 // <32 x half> @llvm.x86.avx512fp16.mask.rndscale.ph.512
7339 // (<32 x half>, i32, <32 x half>, i32, i32)
7340 // <16 x half> @llvm.x86.avx512fp16.mask.rndscale.ph.256
7341 // (<16 x half>, i32, <16 x half>, i32, i16)
7342 // <8 x half> @llvm.x86.avx512fp16.mask.rndscale.ph.128
7343 // (<8 x half>, i32, <8 x half>, i32, i8)
7344 //
7345 // <16 x float> @llvm.x86.avx512.mask.rndscale.ps.512
7346 // (<16 x float>, i32, <16 x float>, i16, i32)
7347 // <8 x float> @llvm.x86.avx512.mask.rndscale.ps.256
7348 // (<8 x float>, i32, <8 x float>, i8)
7349 // <4 x float> @llvm.x86.avx512.mask.rndscale.ps.128
7350 // (<4 x float>, i32, <4 x float>, i8)
7351 //
7352 // <8 x double> @llvm.x86.avx512.mask.rndscale.pd.512
7353 // (<8 x double>, i32, <8 x double>, i8, i32)
7354 // A Imm WriteThru Mask Rounding
7355 // <4 x double> @llvm.x86.avx512.mask.rndscale.pd.256
7356 // (<4 x double>, i32, <4 x double>, i8)
7357 // <2 x double> @llvm.x86.avx512.mask.rndscale.pd.128
7358 // (<2 x double>, i32, <2 x double>, i8)
7359 // A Imm WriteThru Mask
7360 //
7361 // <32 x bfloat> @llvm.x86.avx10.mask.rndscale.bf16.512
7362 // (<32 x bfloat>, i32, <32 x bfloat>, i32)
7363 // <16 x bfloat> @llvm.x86.avx10.mask.rndscale.bf16.256
7364 // (<16 x bfloat>, i32, <16 x bfloat>, i16)
7365 // <8 x bfloat> @llvm.x86.avx10.mask.rndscale.bf16.128
7366 // (<8 x bfloat>, i32, <8 x bfloat>, i8)
7367 //
7368 // Not supported: three vectors
7369 // - <8 x half> @llvm.x86.avx512fp16.mask.rndscale.sh
7370 // (<8 x half>, <8 x half>,<8 x half>, i8, i32, i32)
7371 // - <4 x float> @llvm.x86.avx512.mask.rndscale.ss
7372 // (<4 x float>, <4 x float>, <4 x float>, i8, i32, i32)
7373 // - <2 x double> @llvm.x86.avx512.mask.rndscale.sd
7374 // (<2 x double>, <2 x double>, <2 x double>, i8, i32,
7375 // i32)
7376 // A B WriteThru Mask Imm
7377 // Rounding
7378 case Intrinsic::x86_avx512fp16_mask_rndscale_ph_512:
7379 case Intrinsic::x86_avx512fp16_mask_rndscale_ph_256:
7380 case Intrinsic::x86_avx512fp16_mask_rndscale_ph_128:
7381 case Intrinsic::x86_avx512_mask_rndscale_ps_512:
7382 case Intrinsic::x86_avx512_mask_rndscale_ps_256:
7383 case Intrinsic::x86_avx512_mask_rndscale_ps_128:
7384 case Intrinsic::x86_avx512_mask_rndscale_pd_512:
7385 case Intrinsic::x86_avx512_mask_rndscale_pd_256:
7386 case Intrinsic::x86_avx512_mask_rndscale_pd_128:
7387 case Intrinsic::x86_avx10_mask_rndscale_bf16_512:
7388 case Intrinsic::x86_avx10_mask_rndscale_bf16_256:
7389 case Intrinsic::x86_avx10_mask_rndscale_bf16_128:
7390 handleAVX512VectorGenericMaskedFP(I, /*DataIndices=*/{0},
7391 /*WriteThruIndex=*/2,
7392 /*MaskIndex=*/3);
7393 break;
7394
7395 // AVX512 Vector Scale Float* Packed
7396 //
7397 // < 8 x double> @llvm.x86.avx512.mask.scalef.pd.512
7398 // (<8 x double>, <8 x double>, <8 x double>, i8, i32)
7399 // A B WriteThru Msk Round
7400 // < 4 x double> @llvm.x86.avx512.mask.scalef.pd.256
7401 // (<4 x double>, <4 x double>, <4 x double>, i8)
7402 // < 2 x double> @llvm.x86.avx512.mask.scalef.pd.128
7403 // (<2 x double>, <2 x double>, <2 x double>, i8)
7404 //
7405 // <16 x float> @llvm.x86.avx512.mask.scalef.ps.512
7406 // (<16 x float>, <16 x float>, <16 x float>, i16, i32)
7407 // < 8 x float> @llvm.x86.avx512.mask.scalef.ps.256
7408 // (<8 x float>, <8 x float>, <8 x float>, i8)
7409 // < 4 x float> @llvm.x86.avx512.mask.scalef.ps.128
7410 // (<4 x float>, <4 x float>, <4 x float>, i8)
7411 //
7412 // <32 x half> @llvm.x86.avx512fp16.mask.scalef.ph.512
7413 // (<32 x half>, <32 x half>, <32 x half>, i32, i32)
7414 // <16 x half> @llvm.x86.avx512fp16.mask.scalef.ph.256
7415 // (<16 x half>, <16 x half>, <16 x half>, i16)
7416 // < 8 x half> @llvm.x86.avx512fp16.mask.scalef.ph.128
7417 // (<8 x half>, <8 x half>, <8 x half>, i8)
7418 //
7419 // TODO: AVX10
7420 // <32 x bfloat> @llvm.x86.avx10.mask.scalef.bf16.512
7421 // (<32 x bfloat>, <32 x bfloat>, <32 x bfloat>, i32)
7422 // <16 x bfloat> @llvm.x86.avx10.mask.scalef.bf16.256
7423 // (<16 x bfloat>, <16 x bfloat>, <16 x bfloat>, i16)
7424 // < 8 x bfloat> @llvm.x86.avx10.mask.scalef.bf16.128
7425 // (<8 x bfloat>, <8 x bfloat>, <8 x bfloat>, i8)
7426 case Intrinsic::x86_avx512_mask_scalef_pd_512:
7427 case Intrinsic::x86_avx512_mask_scalef_pd_256:
7428 case Intrinsic::x86_avx512_mask_scalef_pd_128:
7429 case Intrinsic::x86_avx512_mask_scalef_ps_512:
7430 case Intrinsic::x86_avx512_mask_scalef_ps_256:
7431 case Intrinsic::x86_avx512_mask_scalef_ps_128:
7432 case Intrinsic::x86_avx512fp16_mask_scalef_ph_512:
7433 case Intrinsic::x86_avx512fp16_mask_scalef_ph_256:
7434 case Intrinsic::x86_avx512fp16_mask_scalef_ph_128:
7435 // The AVX512 512-bit operand variants have an extra operand (the
7436 // Rounding mode). The extra operand, if present, will be
7437 // automatically checked by the handler.
7438 handleAVX512VectorGenericMaskedFP(I, /*DataIndices=*/{0, 1},
7439 /*WriteThruIndex=*/2,
7440 /*MaskIndex=*/3);
7441 break;
7442
7443 // TODO: AVX512 Vector Scale Float* Scalar
7444 //
7445 // This is different from the Packed variant, because some bits are copied,
7446 // and some bits are zeroed.
7447 //
7448 // < 4 x float> @llvm.x86.avx512.mask.scalef.ss
7449 // (<4 x float>, <4 x float>, <4 x float>, i8, i32)
7450 //
7451 // < 2 x double> @llvm.x86.avx512.mask.scalef.sd
7452 // (<2 x double>, <2 x double>, <2 x double>, i8, i32)
7453 //
7454 // < 8 x half> @llvm.x86.avx512fp16.mask.scalef.sh
7455 // (<8 x half>, <8 x half>, <8 x half>, i8, i32)
7456
7457 // AVX512 FP16 Arithmetic
7458 case Intrinsic::x86_avx512fp16_mask_add_sh_round:
7459 case Intrinsic::x86_avx512fp16_mask_sub_sh_round:
7460 case Intrinsic::x86_avx512fp16_mask_mul_sh_round:
7461 case Intrinsic::x86_avx512fp16_mask_div_sh_round:
7462 case Intrinsic::x86_avx512fp16_mask_max_sh_round:
7463 case Intrinsic::x86_avx512fp16_mask_min_sh_round: {
7464 visitGenericScalarHalfwordInst(I);
7465 break;
7466 }
7467
7468 // AVX512 Floating-Point Classification
7469 // - <8 x i1> @llvm.x86.avx512.fpclass.pd.512(<8 x double>, i32)
7470 // - <16 x i1> @llvm.x86.avx512.fpclass.ps.512(<16 x float>, i32)
7471 case Intrinsic::x86_avx512_fpclass_pd_512:
7472 case Intrinsic::x86_avx512_fpclass_ps_512:
7473 handleAVX512FPClass(I);
7474 break;
7475
7476 // AVX Galois Field New Instructions
7477 case Intrinsic::x86_vgf2p8affineqb_128:
7478 case Intrinsic::x86_vgf2p8affineqb_256:
7479 case Intrinsic::x86_vgf2p8affineqb_512:
7480 handleAVXGF2P8Affine(I);
7481 break;
7482
7483 default:
7484 return false;
7485 }
7486
7487 return true;
7488 }
7489
7490 bool maybeHandleArmSIMDIntrinsic(IntrinsicInst &I) {
7491 switch (I.getIntrinsicID()) {
7492 // Two operands e.g.,
7493 // - <8 x i8> @llvm.aarch64.neon.rshrn.v8i8 (<8 x i16>, i32)
7494 // - <4 x i16> @llvm.aarch64.neon.uqrshl.v4i16(<4 x i16>, <4 x i16>)
7495 case Intrinsic::aarch64_neon_rshrn:
7496 case Intrinsic::aarch64_neon_sqrshl:
7497 case Intrinsic::aarch64_neon_sqrshrn:
7498 case Intrinsic::aarch64_neon_sqrshrun:
7499 case Intrinsic::aarch64_neon_sqshl:
7500 case Intrinsic::aarch64_neon_sqshlu:
7501 case Intrinsic::aarch64_neon_sqshrn:
7502 case Intrinsic::aarch64_neon_sqshrun:
7503 case Intrinsic::aarch64_neon_srshl:
7504 case Intrinsic::aarch64_neon_sshl:
7505 case Intrinsic::aarch64_neon_uqrshl:
7506 case Intrinsic::aarch64_neon_uqrshrn:
7507 case Intrinsic::aarch64_neon_uqshl:
7508 case Intrinsic::aarch64_neon_uqshrn:
7509 case Intrinsic::aarch64_neon_urshl:
7510 case Intrinsic::aarch64_neon_ushl:
7511 handleVectorShiftIntrinsic(I, /* Variable */ false);
7512 break;
7513
7514 // Vector Shift Left/Right and Insert
7515 //
7516 // Three operands e.g.,
7517 // - <4 x i16> @llvm.aarch64.neon.vsli.v4i16
7518 // (<4 x i16> %a, <4 x i16> %b, i32 %n)
7519 // - <16 x i8> @llvm.aarch64.neon.vsri.v16i8
7520 // (<16 x i8> %a, <16 x i8> %b, i32 %n)
7521 //
7522 // %b is shifted by %n bits, and the "missing" bits are filled in with %a
7523 // (instead of zero-extending/sign-extending).
7524 case Intrinsic::aarch64_neon_vsli:
7525 case Intrinsic::aarch64_neon_vsri:
7526 handleIntrinsicByApplyingToShadow(I, I.getIntrinsicID(),
7527 /*verbatimArgIndices=*/{-1},
7528 /*forceIntegerIntrinsic=*/false);
7529 break;
7530
7531 // TODO: handling max/min similarly to AND/OR may be more precise
7532 // Floating-Point Maximum/Minimum Pairwise
7533 case Intrinsic::aarch64_neon_fmaxp:
7534 case Intrinsic::aarch64_neon_fminp:
7535 // Floating-Point Maximum/Minimum Number Pairwise
7536 case Intrinsic::aarch64_neon_fmaxnmp:
7537 case Intrinsic::aarch64_neon_fminnmp:
7538 // Signed/Unsigned Maximum/Minimum Pairwise
7539 case Intrinsic::aarch64_neon_smaxp:
7540 case Intrinsic::aarch64_neon_sminp:
7541 case Intrinsic::aarch64_neon_umaxp:
7542 case Intrinsic::aarch64_neon_uminp:
7543 // Add Pairwise
7544 case Intrinsic::aarch64_neon_addp:
7545 // Floating-point Add Pairwise
7546 case Intrinsic::aarch64_neon_faddp:
7547 // Add Long Pairwise
7548 case Intrinsic::aarch64_neon_saddlp:
7549 case Intrinsic::aarch64_neon_uaddlp: {
7550 handlePairwiseShadowOrIntrinsic(I, /*Shards=*/1);
7551 break;
7552 }
7553
7554 // Floating-point Convert to integer, rounding to nearest with ties to Away
7555 case Intrinsic::aarch64_neon_fcvtas:
7556 case Intrinsic::aarch64_neon_fcvtau:
7557 // Floating-point convert to integer, rounding toward minus infinity
7558 case Intrinsic::aarch64_neon_fcvtms:
7559 case Intrinsic::aarch64_neon_fcvtmu:
7560 // Floating-point convert to integer, rounding to nearest with ties to even
7561 case Intrinsic::aarch64_neon_fcvtns:
7562 case Intrinsic::aarch64_neon_fcvtnu:
7563 // Floating-point convert to integer, rounding toward plus infinity
7564 case Intrinsic::aarch64_neon_fcvtps:
7565 case Intrinsic::aarch64_neon_fcvtpu:
7566 // Floating-point Convert to integer, rounding toward Zero
7567 case Intrinsic::aarch64_neon_fcvtzs:
7568 case Intrinsic::aarch64_neon_fcvtzu:
7569 // Floating-point convert to lower precision narrow, rounding to odd
7570 case Intrinsic::aarch64_neon_fcvtxn:
7571 handleGenericVectorConvertIntrinsic(I, /*FixedPoint=*/false);
7572 break;
7573
7574 // Vector Conversions Between Fixed-Point and Floating-Point
7575 case Intrinsic::aarch64_neon_vcvtfxs2fp:
7576 case Intrinsic::aarch64_neon_vcvtfp2fxs:
7577 case Intrinsic::aarch64_neon_vcvtfxu2fp:
7578 case Intrinsic::aarch64_neon_vcvtfp2fxu:
7579 handleGenericVectorConvertIntrinsic(I, /*FixedPoint=*/true);
7580 break;
7581
7582 // TODO: bfloat conversions
7583 // - bfloat @llvm.aarch64.neon.bfcvt(float)
7584 // - <8 x bfloat> @llvm.aarch64.neon.bfcvtn(<4 x float>)
7585 // - <8 x bfloat> @llvm.aarch64.neon.bfcvtn2(<8 x bfloat>, <4 x float>)
7586
7587 // Add reduction to scalar
7588 case Intrinsic::aarch64_neon_faddv:
7589 case Intrinsic::aarch64_neon_saddv:
7590 case Intrinsic::aarch64_neon_uaddv:
7591 // Signed/Unsigned min/max (Vector)
7592 // TODO: handling similarly to AND/OR may be more precise.
7593 case Intrinsic::aarch64_neon_smaxv:
7594 case Intrinsic::aarch64_neon_sminv:
7595 case Intrinsic::aarch64_neon_umaxv:
7596 case Intrinsic::aarch64_neon_uminv:
7597 // Floating-point min/max (vector)
7598 // The f{min,max}"nm"v variants handle NaN differently than f{min,max}v,
7599 // but our shadow propagation is the same.
7600 case Intrinsic::aarch64_neon_fmaxv:
7601 case Intrinsic::aarch64_neon_fminv:
7602 case Intrinsic::aarch64_neon_fmaxnmv:
7603 case Intrinsic::aarch64_neon_fminnmv:
7604 // Sum long across vector
7605 case Intrinsic::aarch64_neon_saddlv:
7606 case Intrinsic::aarch64_neon_uaddlv:
7607 handleVectorReduceIntrinsic(I, /*AllowShadowCast=*/true);
7608 break;
7609
7610 case Intrinsic::aarch64_neon_ld1x2:
7611 case Intrinsic::aarch64_neon_ld1x3:
7612 case Intrinsic::aarch64_neon_ld1x4:
7613 case Intrinsic::aarch64_neon_ld2:
7614 case Intrinsic::aarch64_neon_ld3:
7615 case Intrinsic::aarch64_neon_ld4:
7616 case Intrinsic::aarch64_neon_ld2r:
7617 case Intrinsic::aarch64_neon_ld3r:
7618 case Intrinsic::aarch64_neon_ld4r: {
7619 handleNEONVectorLoad(I, /*WithLane=*/false);
7620 break;
7621 }
7622
7623 case Intrinsic::aarch64_neon_ld2lane:
7624 case Intrinsic::aarch64_neon_ld3lane:
7625 case Intrinsic::aarch64_neon_ld4lane: {
7626 handleNEONVectorLoad(I, /*WithLane=*/true);
7627 break;
7628 }
7629
7630 // Saturating extract narrow
7631 case Intrinsic::aarch64_neon_sqxtn:
7632 case Intrinsic::aarch64_neon_sqxtun:
7633 case Intrinsic::aarch64_neon_uqxtn:
7634 // These only have one argument, but we (ab)use handleShadowOr because it
7635 // does work on single argument intrinsics and will typecast the shadow
7636 // (and update the origin).
7637 handleShadowOr(I);
7638 break;
7639
7640 case Intrinsic::aarch64_neon_st1x2:
7641 case Intrinsic::aarch64_neon_st1x3:
7642 case Intrinsic::aarch64_neon_st1x4:
7643 case Intrinsic::aarch64_neon_st2:
7644 case Intrinsic::aarch64_neon_st3:
7645 case Intrinsic::aarch64_neon_st4: {
7646 handleNEONVectorStoreIntrinsic(I, false);
7647 break;
7648 }
7649
7650 case Intrinsic::aarch64_neon_st2lane:
7651 case Intrinsic::aarch64_neon_st3lane:
7652 case Intrinsic::aarch64_neon_st4lane: {
7653 handleNEONVectorStoreIntrinsic(I, true);
7654 break;
7655 }
7656
7657 // Arm NEON vector table intrinsics have the source/table register(s) as
7658 // arguments, followed by the index register. They return the output.
7659 //
7660 // 'TBL writes a zero if an index is out-of-range, while TBX leaves the
7661 // original value unchanged in the destination register.'
7662 // Conveniently, zero denotes a clean shadow, which means out-of-range
7663 // indices for TBL will initialize the user data with zero and also clean
7664 // the shadow. (For TBX, neither the user data nor the shadow will be
7665 // updated, which is also correct.)
7666 case Intrinsic::aarch64_neon_tbl1:
7667 case Intrinsic::aarch64_neon_tbl2:
7668 case Intrinsic::aarch64_neon_tbl3:
7669 case Intrinsic::aarch64_neon_tbl4:
7670 case Intrinsic::aarch64_neon_tbx1:
7671 case Intrinsic::aarch64_neon_tbx2:
7672 case Intrinsic::aarch64_neon_tbx3:
7673 case Intrinsic::aarch64_neon_tbx4: {
7674 // The last trailing argument (index register) should be handled verbatim
7675 handleIntrinsicByApplyingToShadow(
7676 I, /*shadowIntrinsicID=*/I.getIntrinsicID(),
7677 /*verbatimArgIndices=*/{-1}, /*forceIntegerIntrinsic=*/false);
7678 break;
7679 }
7680
7681 case Intrinsic::aarch64_neon_fmulx:
7682 case Intrinsic::aarch64_neon_pmul:
7683 case Intrinsic::aarch64_neon_pmull:
7684 case Intrinsic::aarch64_neon_smull:
7685 case Intrinsic::aarch64_neon_pmull64:
7686 case Intrinsic::aarch64_neon_umull: {
7687 handleNEONVectorMultiplyIntrinsic(I);
7688 break;
7689 }
7690
7691 case Intrinsic::aarch64_neon_smmla:
7692 case Intrinsic::aarch64_neon_ummla:
7693 case Intrinsic::aarch64_neon_usmmla:
7694 case Intrinsic::aarch64_neon_bfmmla:
7695 handleNEONMatrixMultiply(I);
7696 break;
7697
7698 // <2 x i32> @llvm.aarch64.neon.{u,s,us}dot.v2i32.v8i8
7699 // (<2 x i32> %acc, <8 x i8> %a, <8 x i8> %b)
7700 // <4 x i32> @llvm.aarch64.neon.{u,s,us}dot.v4i32.v16i8
7701 // (<4 x i32> %acc, <16 x i8> %a, <16 x i8> %b)
7702 case Intrinsic::aarch64_neon_sdot:
7703 case Intrinsic::aarch64_neon_udot:
7704 case Intrinsic::aarch64_neon_usdot:
7705 handleVectorDotProductIntrinsic(I, /*ReductionFactor=*/4,
7706 /*ZeroPurifies=*/true,
7707 /*EltSizeInBits=*/0,
7708 /*Lanes=*/kBothLanes);
7709 break;
7710
7711 // <2 x float> @llvm.aarch64.neon.bfdot.v2f32.v4bf16
7712 // (<2 x float> %acc, <4 x bfloat> %a, <4 x bfloat> %b)
7713 // <4 x float> @llvm.aarch64.neon.bfdot.v4f32.v8bf16
7714 // (<4 x float> %acc, <8 x bfloat> %a, <8 x bfloat> %b)
7715 case Intrinsic::aarch64_neon_bfdot:
7716 handleVectorDotProductIntrinsic(I, /*ReductionFactor=*/2,
7717 /*ZeroPurifies=*/false,
7718 /*EltSizeInBits=*/0,
7719 /*Lanes=*/kBothLanes);
7720 break;
7721
7722 // <4 x half > @llvm.aarch64.neon.fp8.fdot2
7723 // (<4 x half >, < 8 x i8>, < 8 x i8>)
7724 // <8 x half > @llvm.aarch64.neon.fp8.fdot2
7725 // (<8 x half >, <16 x i8>, <16 x i8>)
7726 //
7727 // N.B. although the multiplicands are i8, they are actually fp8, thus
7728 // ZeroPurifies is not applicable.
7729 case Intrinsic::aarch64_neon_fp8_fdot2:
7730 handleVectorDotProductIntrinsic(I, /*ReductionFactor=*/2,
7731 /*ZeroPurifies=*/false,
7732 /*EltSizeInBits=*/0,
7733 /*Lanes=*/kBothLanes);
7734 break;
7735
7736 // <2 x float> @llvm.aarch64.neon.fp8.fdot4
7737 // (<2 x float>, < 8 x i8>, < 8 x i8>)
7738 // <4 x float> @llvm.aarch64.neon.fp8.fdot4
7739 // (<4 x float>, <16 x i8>, <16 x i8>)
7740 //
7741 // N.B. although the multiplicands are i8, they are actually fp8, thus
7742 // ZeroPurifies is not applicable.
7743 case Intrinsic::aarch64_neon_fp8_fdot4:
7744 handleVectorDotProductIntrinsic(I, /*ReductionFactor=*/4,
7745 /*ZeroPurifies=*/false,
7746 /*EltSizeInBits=*/0,
7747 /*Lanes=*/kBothLanes);
7748 break;
7749
7750 // <4 x half> @llvm.aarch64.neon.fp8.fdot2.lane
7751 // (<4 x half>, <8 x i8>, <16 x i8>, i32)
7752 // <8 x half> @llvm.aarch64.neon.fp8.fdot2.lane
7753 // (<8 x half>, <16 x i8>, <16 x i8>, i32)
7754 case Intrinsic::aarch64_neon_fp8_fdot2_lane:
7755 handleNEONDotProductLaneIntrinsic(I, /*ReductionFactor=*/2);
7756 break;
7757
7758 // <2 x float> @llvm.aarch64.neon.fp8.fdot4.lane
7759 // (<2 x float>, <8 x i8>, <16 x i8>, i32)
7760 // <4 x float> @llvm.aarch64.neon.fp8.fdot4.lane
7761 // (<4 x float>, <16 x i8>, <16 x i8>, i32)
7762 case Intrinsic::aarch64_neon_fp8_fdot4_lane:
7763 handleNEONDotProductLaneIntrinsic(I, /*ReductionFactor=*/4);
7764 break;
7765
7766 // Floating-Point Absolute Compare Greater Than/Equal
7767 case Intrinsic::aarch64_neon_facge:
7768 case Intrinsic::aarch64_neon_facgt:
7769 handleVectorComparePackedIntrinsic(I, /*PredicateAsOperand=*/false);
7770 break;
7771
7772 default:
7773 return false;
7774 }
7775
7776 return true;
7777 }
7778
7779 void visitIntrinsicInst(IntrinsicInst &I) {
7780 if (maybeHandleUntrackedMemoryIntrinsic(I))
7781 return;
7782
7783 if (maybeHandleCrossPlatformIntrinsic(I))
7784 return;
7785
7786 if (maybeHandleX86SIMDIntrinsic(I))
7787 return;
7788
7789 if (maybeHandleArmSIMDIntrinsic(I))
7790 return;
7791
7792 if (maybeHandleUnknownIntrinsic(I))
7793 return;
7794
7795 visitInstruction(I);
7796 }
7797
7798 void visitLibAtomicLoad(CallBase &CB) {
7799 // Since we use getNextNode here, we can't have CB terminate the BB.
7800 assert(isa<CallInst>(CB));
7801
7802 IRBuilder<> IRB(&CB);
7803 Value *Size = CB.getArgOperand(0);
7804 Value *SrcPtr = CB.getArgOperand(1);
7805 Value *DstPtr = CB.getArgOperand(2);
7806 Value *Ordering = CB.getArgOperand(3);
7807 // Convert the call to have at least Acquire ordering to make sure
7808 // the shadow operations aren't reordered before it.
7809 Value *NewOrdering =
7810 IRB.CreateExtractElement(makeAddAcquireOrderingTable(IRB), Ordering);
7811 CB.setArgOperand(3, NewOrdering);
7812
7813 NextNodeIRBuilder NextIRB(&CB);
7814 Value *SrcShadowPtr, *SrcOriginPtr;
7815 std::tie(SrcShadowPtr, SrcOriginPtr) =
7816 getShadowOriginPtr(SrcPtr, NextIRB, NextIRB.getInt8Ty(), Align(1),
7817 /*isStore*/ false);
7818 Value *DstShadowPtr =
7819 getShadowOriginPtr(DstPtr, NextIRB, NextIRB.getInt8Ty(), Align(1),
7820 /*isStore*/ true)
7821 .first;
7822
7823 NextIRB.CreateMemCpy(DstShadowPtr, Align(1), SrcShadowPtr, Align(1), Size);
7824 if (MS.TrackOrigins) {
7825 Value *SrcOrigin = NextIRB.CreateAlignedLoad(MS.OriginTy, SrcOriginPtr,
7827 Value *NewOrigin = updateOrigin(SrcOrigin, NextIRB);
7828 NextIRB.CreateCall(MS.MsanSetOriginFn, {DstPtr, Size, NewOrigin});
7829 }
7830 }
7831
7832 void visitLibAtomicStore(CallBase &CB) {
7833 IRBuilder<> IRB(&CB);
7834 Value *Size = CB.getArgOperand(0);
7835 Value *DstPtr = CB.getArgOperand(2);
7836 Value *Ordering = CB.getArgOperand(3);
7837 // Convert the call to have at least Release ordering to make sure
7838 // the shadow operations aren't reordered after it.
7839 Value *NewOrdering =
7840 IRB.CreateExtractElement(makeAddReleaseOrderingTable(IRB), Ordering);
7841 CB.setArgOperand(3, NewOrdering);
7842
7843 Value *DstShadowPtr =
7844 getShadowOriginPtr(DstPtr, IRB, IRB.getInt8Ty(), Align(1),
7845 /*isStore*/ true)
7846 .first;
7847
7848 // Atomic store always paints clean shadow/origin. See file header.
7849 IRB.CreateMemSet(DstShadowPtr, getCleanShadow(IRB.getInt8Ty()), Size,
7850 Align(1));
7851 }
7852
7853 void visitCallBase(CallBase &CB) {
7854 assert(!CB.getMetadata(LLVMContext::MD_nosanitize));
7855 if (CB.isInlineAsm()) {
7856 // For inline asm (either a call to asm function, or callbr instruction),
7857 // do the usual thing: check argument shadow and mark all outputs as
7858 // clean. Note that any side effects of the inline asm that are not
7859 // immediately visible in its constraints are not handled.
7860 if (Opts.msan_handle_asm_conservative)
7861 visitAsmInstruction(CB);
7862 else
7863 visitInstruction(CB);
7864 return;
7865 }
7866 LibFunc LF = TLI->getLibFunc(CB);
7867 if (LF != NotLibFunc) {
7868 // libatomic.a functions need to have special handling because there isn't
7869 // a good way to intercept them or compile the library with
7870 // instrumentation.
7871 switch (LF) {
7872 case LibFunc_atomic_load:
7873 if (!isa<CallInst>(CB)) {
7874 llvm::errs() << "MSAN -- cannot instrument invoke of libatomic load."
7875 "Ignoring!\n";
7876 break;
7877 }
7878 visitLibAtomicLoad(CB);
7879 return;
7880 case LibFunc_atomic_store:
7881 visitLibAtomicStore(CB);
7882 return;
7883 default:
7884 break;
7885 }
7886 }
7887
7888 if (auto *Call = dyn_cast<CallInst>(&CB)) {
7889 assert(!isa<IntrinsicInst>(Call) && "intrinsics are handled elsewhere");
7890
7891 // We are going to insert code that relies on the fact that the callee
7892 // will become a non-readonly function after it is instrumented by us. To
7893 // prevent this code from being optimized out, mark that function
7894 // non-readonly in advance.
7895 // TODO: We can likely do better than dropping memory() completely here.
7896 AttributeMask B;
7897 B.addAttribute(Attribute::Memory).addAttribute(Attribute::Speculatable);
7898
7900 if (Function *Func = Call->getCalledFunction()) {
7901 Func->removeFnAttrs(B);
7902 }
7903
7905 }
7906 IRBuilder<> IRB(&CB);
7907 bool MayCheckCall = MS.EagerChecks;
7908 if (Function *Func = CB.getCalledFunction()) {
7909 // __sanitizer_unaligned_{load,store} functions may be called by users
7910 // and always expects shadows in the TLS. So don't check them.
7911 MayCheckCall &= !Func->getName().starts_with("__sanitizer_unaligned_");
7912 }
7913
7914 unsigned ArgOffset = 0;
7915 LLVM_DEBUG(dbgs() << " CallSite: " << CB << "\n");
7916 for (const auto &[i, A] : llvm::enumerate(CB.args())) {
7917 if (!A->getType()->isSized()) {
7918 LLVM_DEBUG(dbgs() << "Arg " << i << " is not sized: " << CB << "\n");
7919 continue;
7920 }
7921
7922 if (A->getType()->isScalableTy()) {
7923 LLVM_DEBUG(dbgs() << "Arg " << i << " is vscale: " << CB << "\n");
7924 // Handle as noundef, but don't reserve tls slots.
7925 insertCheckShadowOf(A, &CB);
7926 continue;
7927 }
7928
7929 unsigned Size = 0;
7930 const DataLayout &DL = F.getDataLayout();
7931
7932 bool ByVal = CB.isByValArgument(i);
7933 bool NoUndef = CB.paramHasAttr(i, Attribute::NoUndef);
7934 bool EagerCheck = MayCheckCall && !ByVal && NoUndef;
7935
7936 if (EagerCheck) {
7937 insertCheckShadowOf(A, &CB);
7938 Size = DL.getTypeAllocSize(A->getType());
7939 } else {
7940 [[maybe_unused]] Value *Store = nullptr;
7941 // Compute the Shadow for arg even if it is ByVal, because
7942 // in that case getShadow() will copy the actual arg shadow to
7943 // __msan_param_tls.
7944 Value *ArgShadow = getShadow(A);
7945 Value *ArgShadowBase = getShadowPtrForArgument(IRB, ArgOffset);
7946 LLVM_DEBUG(dbgs() << " Arg#" << i << ": " << *A
7947 << " Shadow: " << *ArgShadow << "\n");
7948 if (ByVal) {
7949 // ByVal requires some special handling as it's too big for a single
7950 // load
7951 assert(A->getType()->isPointerTy() &&
7952 "ByVal argument is not a pointer!");
7953 Size = DL.getTypeAllocSize(CB.getParamByValType(i));
7954 if (ArgOffset + Size > kParamTLSSize)
7955 break;
7956 const MaybeAlign ParamAlignment(CB.getParamAlign(i));
7957 MaybeAlign Alignment = std::nullopt;
7958 if (ParamAlignment)
7959 Alignment = std::min(*ParamAlignment, kShadowTLSAlignment);
7960 Value *AShadowPtr, *AOriginPtr;
7961 std::tie(AShadowPtr, AOriginPtr) =
7962 getShadowOriginPtr(A, IRB, IRB.getInt8Ty(), Alignment,
7963 /*isStore*/ false);
7964 if (!PropagateShadow) {
7965 Store = IRB.CreateMemSet(ArgShadowBase,
7967 Size, Alignment);
7968 } else {
7969 Store = IRB.CreateMemCpy(ArgShadowBase, Alignment, AShadowPtr,
7970 Alignment, Size);
7971 if (MS.TrackOrigins) {
7972 Value *ArgOriginBase = getOriginPtrForArgument(IRB, ArgOffset);
7973 // FIXME: OriginSize should be:
7974 // alignTo(A % kMinOriginAlignment + Size, kMinOriginAlignment)
7975 unsigned OriginSize = alignTo(Size, kMinOriginAlignment);
7976 IRB.CreateMemCpy(
7977 ArgOriginBase,
7978 /* by origin_tls[ArgOffset] */ kMinOriginAlignment,
7979 AOriginPtr,
7980 /* by getShadowOriginPtr */ kMinOriginAlignment, OriginSize);
7981 }
7982 }
7983 } else {
7984 // Any other parameters mean we need bit-grained tracking of uninit
7985 // data
7986 Size = DL.getTypeAllocSize(A->getType());
7987 if (ArgOffset + Size > kParamTLSSize)
7988 break;
7989 Store = IRB.CreateAlignedStore(ArgShadow, ArgShadowBase,
7991 Constant *Cst = dyn_cast<Constant>(ArgShadow);
7992 if (MS.TrackOrigins && !(Cst && Cst->isNullValue())) {
7993 IRB.CreateStore(getOrigin(A),
7994 getOriginPtrForArgument(IRB, ArgOffset));
7995 }
7996 }
7997 assert(Store != nullptr);
7998 LLVM_DEBUG(dbgs() << " Param:" << *Store << "\n");
7999 }
8000 assert(Size != 0);
8001 ArgOffset += alignTo(Size, kShadowTLSAlignment);
8002 }
8003 LLVM_DEBUG(dbgs() << " done with call args\n");
8004
8005 FunctionType *FT = CB.getFunctionType();
8006 if (FT->isVarArg()) {
8007 VAHelper->visitCallBase(CB, IRB);
8008 }
8009
8010 // Now, get the shadow for the RetVal.
8011 if (!CB.getType()->isSized())
8012 return;
8013 // Don't emit the epilogue for musttail call returns.
8014 if (isa<CallInst>(CB) && cast<CallInst>(CB).isMustTailCall())
8015 return;
8016
8017 if (MayCheckCall && CB.hasRetAttr(Attribute::NoUndef)) {
8018 setShadow(&CB, getCleanShadow(&CB));
8019 setOrigin(&CB, getCleanOrigin());
8020 return;
8021 }
8022
8023 IRBuilder<> IRBBefore(&CB);
8024 // Until we have full dynamic coverage, make sure the retval shadow is 0.
8025 Value *Base = getShadowPtrForRetval(IRBBefore);
8026 IRBBefore.CreateAlignedStore(getCleanShadow(&CB), Base,
8028 BasicBlock::iterator NextInsn;
8029 if (isa<CallInst>(CB)) {
8030 NextInsn = ++CB.getIterator();
8031 assert(NextInsn != CB.getParent()->end());
8032 } else {
8033 BasicBlock *NormalDest = cast<InvokeInst>(CB).getNormalDest();
8034 if (!NormalDest->getSinglePredecessor()) {
8035 // FIXME: this case is tricky, so we are just conservative here.
8036 // Perhaps we need to split the edge between this BB and NormalDest,
8037 // but a naive attempt to use SplitEdge leads to a crash.
8038 setShadow(&CB, getCleanShadow(&CB));
8039 setOrigin(&CB, getCleanOrigin());
8040 return;
8041 }
8042 // FIXME: NextInsn is likely in a basic block that has not been visited
8043 // yet. Anything inserted there will be instrumented by MSan later!
8044 NextInsn = NormalDest->getFirstInsertionPt();
8045 assert(NextInsn != NormalDest->end() &&
8046 "Could not find insertion point for retval shadow load");
8047 }
8048 IRBuilder<> IRBAfter(&*NextInsn);
8049 Value *RetvalShadow = IRBAfter.CreateAlignedLoad(
8050 getShadowTy(&CB), getShadowPtrForRetval(IRBAfter), kShadowTLSAlignment,
8051 "_msret");
8052 setShadow(&CB, RetvalShadow);
8053 if (MS.TrackOrigins)
8054 setOrigin(&CB, IRBAfter.CreateLoad(MS.OriginTy, getOriginPtrForRetval()));
8055 }
8056
8057 bool isAMustTailRetVal(Value *RetVal) {
8058 if (auto *I = dyn_cast<BitCastInst>(RetVal)) {
8059 RetVal = I->getOperand(0);
8060 }
8061 if (auto *I = dyn_cast<CallInst>(RetVal)) {
8062 return I->isMustTailCall();
8063 }
8064 return false;
8065 }
8066
8067 void visitReturnInst(ReturnInst &I) {
8068 IRBuilder<> IRB(&I);
8069 Value *RetVal = I.getReturnValue();
8070 if (!RetVal)
8071 return;
8072 // Don't emit the epilogue for musttail call returns.
8073 if (isAMustTailRetVal(RetVal))
8074 return;
8075 Value *ShadowPtr = getShadowPtrForRetval(IRB);
8076 bool HasNoUndef = F.hasRetAttribute(Attribute::NoUndef);
8077 bool StoreShadow = !(MS.EagerChecks && HasNoUndef);
8078 // FIXME: Consider using SpecialCaseList to specify a list of functions that
8079 // must always return fully initialized values. For now, we hardcode "main".
8080 bool EagerCheck = (MS.EagerChecks && HasNoUndef) || (F.getName() == "main");
8081
8082 Value *Shadow = getShadow(RetVal);
8083 bool StoreOrigin = true;
8084 if (EagerCheck) {
8085 insertCheckShadowOf(RetVal, &I);
8086 Shadow = getCleanShadow(RetVal);
8087 StoreOrigin = false;
8088 }
8089
8090 // The caller may still expect information passed over TLS if we pass our
8091 // check
8092 if (StoreShadow) {
8093 IRB.CreateAlignedStore(Shadow, ShadowPtr, kShadowTLSAlignment);
8094 if (MS.TrackOrigins && StoreOrigin)
8095 IRB.CreateStore(getOrigin(RetVal), getOriginPtrForRetval());
8096 }
8097 }
8098
8099 void visitPHINode(PHINode &I) {
8100 IRBuilder<> IRB(&I);
8101 if (!PropagateShadow) {
8102 setShadow(&I, getCleanShadow(&I));
8103 setOrigin(&I, getCleanOrigin());
8104 return;
8105 }
8106
8107 ShadowPHINodes.push_back(&I);
8108 setShadow(&I, IRB.CreatePHI(getShadowTy(&I), I.getNumIncomingValues(),
8109 "_msphi_s"));
8110 if (MS.TrackOrigins)
8111 setOrigin(
8112 &I, IRB.CreatePHI(MS.OriginTy, I.getNumIncomingValues(), "_msphi_o"));
8113 }
8114
8115 Value *getLocalVarIdptr(AllocaInst &I) {
8116 ConstantInt *IntConst =
8117 ConstantInt::get(Type::getInt32Ty((*F.getParent()).getContext()), 0);
8118 return new GlobalVariable(*F.getParent(), IntConst->getType(),
8119 /*isConstant=*/false, GlobalValue::PrivateLinkage,
8120 IntConst);
8121 }
8122
8123 Value *getLocalVarDescription(AllocaInst &I) {
8124 return createPrivateConstGlobalForString(*F.getParent(), I.getName());
8125 }
8126
8127 void poisonAllocaUserspace(AllocaInst &I, IRBuilder<> &IRB, Value *Len) {
8128 if (PoisonStack && Opts.msan_poison_stack_with_call) {
8129 IRB.CreateCall(MS.MsanPoisonStackFn, {&I, Len});
8130 } else {
8131 Value *ShadowBase, *OriginBase;
8132 std::tie(ShadowBase, OriginBase) = getShadowOriginPtr(
8133 &I, IRB, IRB.getInt8Ty(), Align(1), /*isStore*/ true);
8134
8135 Value *PoisonValue =
8136 IRB.getInt8(PoisonStack ? Opts.msan_poison_stack_pattern : 0);
8137 IRB.CreateMemSet(ShadowBase, PoisonValue, Len, I.getAlign());
8138 }
8139
8140 if (PoisonStack && MS.TrackOrigins) {
8141 Value *Idptr = getLocalVarIdptr(I);
8142 if (Opts.msan_print_stack_names) {
8143 Value *Descr = getLocalVarDescription(I);
8144 IRB.CreateCall(MS.MsanSetAllocaOriginWithDescriptionFn,
8145 {&I, Len, Idptr, Descr});
8146 } else {
8147 IRB.CreateCall(MS.MsanSetAllocaOriginNoDescriptionFn, {&I, Len, Idptr});
8148 }
8149 }
8150 }
8151
8152 void poisonAllocaKmsan(AllocaInst &I, IRBuilder<> &IRB, Value *Len) {
8153 Value *Descr = getLocalVarDescription(I);
8154 if (PoisonStack) {
8155 IRB.CreateCall(MS.MsanPoisonAllocaFn, {&I, Len, Descr});
8156 } else {
8157 IRB.CreateCall(MS.MsanUnpoisonAllocaFn, {&I, Len});
8158 }
8159 }
8160
8161 void instrumentAlloca(AllocaInst &I, Instruction *InsPoint = nullptr) {
8162 if (!InsPoint)
8163 InsPoint = &I;
8164 NextNodeIRBuilder IRB(InsPoint);
8165 Value *Len = IRB.CreateAllocationSize(MS.IntptrTy, &I);
8166
8167 if (MS.CompileKernel)
8168 poisonAllocaKmsan(I, IRB, Len);
8169 else
8170 poisonAllocaUserspace(I, IRB, Len);
8171 }
8172
8173 void visitAllocaInst(AllocaInst &I) {
8174 setShadow(&I, getCleanShadow(&I));
8175 setOrigin(&I, getCleanOrigin());
8176 // We'll get to this alloca later unless it's poisoned at the corresponding
8177 // llvm.lifetime.start.
8178 AllocaSet.insert(&I);
8179 }
8180
8181 void visitSelectInst(SelectInst &I) {
8182 // a = select b, c, d
8183 Value *B = I.getCondition();
8184 Value *C = I.getTrueValue();
8185 Value *D = I.getFalseValue();
8186
8187 handleSelectLikeInst(I, B, C, D);
8188 }
8189
8190 void handleSelectLikeInst(Instruction &I, Value *B, Value *C, Value *D) {
8191 IRBuilder<> IRB(&I);
8192
8193 Value *Sb = getShadow(B);
8194 Value *Sc = getShadow(C);
8195 Value *Sd = getShadow(D);
8196
8197 Value *Ob = MS.TrackOrigins ? getOrigin(B) : nullptr;
8198 Value *Oc = MS.TrackOrigins ? getOrigin(C) : nullptr;
8199 Value *Od = MS.TrackOrigins ? getOrigin(D) : nullptr;
8200
8201 // Result shadow if condition shadow is 0.
8202 Value *Sa0 = IRB.CreateSelect(B, Sc, Sd);
8203 Value *Sa1;
8204 if (I.getType()->isAggregateType()) {
8205 // To avoid "sign extending" i1 to an arbitrary aggregate type, we just do
8206 // an extra "select". This results in much more compact IR.
8207 // Sa = select Sb, poisoned, (select b, Sc, Sd)
8208 Sa1 = getPoisonedShadow(getShadowTy(I.getType()));
8209 } else if (isScalableNonVectorType(I.getType())) {
8210 // This is intended to handle target("aarch64.svcount"), which can't be
8211 // handled in the else branch because of incompatibility with CreateXor
8212 // ("The supported LLVM operations on this type are limited to load,
8213 // store, phi, select and alloca instructions").
8214
8215 // TODO: this currently underapproximates. Use Arm SVE EOR in the else
8216 // branch as needed instead.
8217 Sa1 = getCleanShadow(getShadowTy(I.getType()));
8218 } else {
8219 // Sa = select Sb, [ (c^d) | Sc | Sd ], [ b ? Sc : Sd ]
8220 // If Sb (condition is poisoned), look for bits in c and d that are equal
8221 // and both unpoisoned.
8222 // If !Sb (condition is unpoisoned), simply pick one of Sc and Sd.
8223
8224 // Cast arguments to shadow-compatible type.
8225 C = CreateAppToShadowCast(IRB, C);
8226 D = CreateAppToShadowCast(IRB, D);
8227
8228 // Result shadow if condition shadow is 1.
8229 Sa1 = IRB.CreateOr({IRB.CreateXor(C, D), Sc, Sd});
8230 }
8231 Value *Sa = IRB.CreateSelect(Sb, Sa1, Sa0, "_msprop_select");
8232 setShadow(&I, Sa);
8233 if (MS.TrackOrigins) {
8234 // Origins are always i32, so any vector conditions must be flattened.
8235 // FIXME: consider tracking vector origins for app vectors?
8236 if (B->getType()->isVectorTy()) {
8237 B = convertToBool(B, IRB);
8238 Sb = convertToBool(Sb, IRB);
8239 }
8240 // a = select b, c, d
8241 // Oa = Sb ? Ob : (b ? Oc : Od)
8242 setOrigin(&I, IRB.CreateSelect(Sb, Ob, IRB.CreateSelect(B, Oc, Od)));
8243 }
8244 }
8245
8246 void visitLandingPadInst(LandingPadInst &I) {
8247 // Do nothing.
8248 // See https://github.com/google/sanitizers/issues/504
8249 setShadow(&I, getCleanShadow(&I));
8250 setOrigin(&I, getCleanOrigin());
8251 }
8252
8253 void visitCatchSwitchInst(CatchSwitchInst &I) {
8254 setShadow(&I, getCleanShadow(&I));
8255 setOrigin(&I, getCleanOrigin());
8256 }
8257
8258 void visitFuncletPadInst(FuncletPadInst &I) {
8259 setShadow(&I, getCleanShadow(&I));
8260 setOrigin(&I, getCleanOrigin());
8261 }
8262
8263 void visitGetElementPtrInst(GetElementPtrInst &I) { handleShadowOr(I); }
8264
8265 void visitExtractValueInst(ExtractValueInst &I) {
8266 IRBuilder<> IRB(&I);
8267 Value *Agg = I.getAggregateOperand();
8268 LLVM_DEBUG(dbgs() << "ExtractValue: " << I << "\n");
8269 Value *AggShadow = getShadow(Agg);
8270 LLVM_DEBUG(dbgs() << " AggShadow: " << *AggShadow << "\n");
8271 Value *ResShadow = IRB.CreateExtractValue(AggShadow, I.getIndices());
8272 LLVM_DEBUG(dbgs() << " ResShadow: " << *ResShadow << "\n");
8273 setShadow(&I, ResShadow);
8274 setOriginForNaryOp(I);
8275 }
8276
8277 void visitInsertValueInst(InsertValueInst &I) {
8278 IRBuilder<> IRB(&I);
8279 LLVM_DEBUG(dbgs() << "InsertValue: " << I << "\n");
8280 Value *AggShadow = getShadow(I.getAggregateOperand());
8281 Value *InsShadow = getShadow(I.getInsertedValueOperand());
8282 LLVM_DEBUG(dbgs() << " AggShadow: " << *AggShadow << "\n");
8283 LLVM_DEBUG(dbgs() << " InsShadow: " << *InsShadow << "\n");
8284 Value *Res = IRB.CreateInsertValue(AggShadow, InsShadow, I.getIndices());
8285 LLVM_DEBUG(dbgs() << " Res: " << *Res << "\n");
8286 setShadow(&I, Res);
8287 setOriginForNaryOp(I);
8288 }
8289
8290 void dumpInst(Instruction &I, const Twine &Prefix) {
8291 // Instruction name only
8292 // For intrinsics, the full/overloaded name is used
8293 //
8294 // e.g., "call llvm.aarch64.neon.uqsub.v16i8"
8295 if (CallInst *CI = dyn_cast<CallInst>(&I)) {
8296 errs() << "ZZZ:" << Prefix << " call "
8297 << CI->getCalledFunction()->getName() << "\n";
8298 } else {
8299 errs() << "ZZZ:" << Prefix << " " << I.getOpcodeName() << "\n";
8300 }
8301
8302 // Instruction prototype (including return type and parameter types)
8303 // For intrinsics, we use the base/non-overloaded name
8304 //
8305 // e.g., "call <16 x i8> @llvm.aarch64.neon.uqsub(<16 x i8>, <16 x i8>)"
8306 unsigned NumOperands = I.getNumOperands();
8307 if (CallInst *CI = dyn_cast<CallInst>(&I)) {
8308 errs() << "YYY:" << Prefix << " call " << *I.getType() << " @";
8309
8310 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(CI))
8311 errs() << Intrinsic::getBaseName(II->getIntrinsicID());
8312 else
8313 errs() << CI->getCalledFunction()->getName();
8314
8315 errs() << "(";
8316
8317 // The last operand of a CallInst is the function itself.
8318 NumOperands--;
8319 } else
8320 errs() << "YYY:" << Prefix << " " << *I.getType() << " "
8321 << I.getOpcodeName() << "(";
8322
8323 for (size_t i = 0; i < NumOperands; i++) {
8324 if (i > 0)
8325 errs() << ", ";
8326
8327 errs() << *(I.getOperand(i)->getType());
8328 }
8329
8330 errs() << ")\n";
8331
8332 // Full instruction, including types and operand values
8333 // For intrinsics, the full/overloaded name is used
8334 //
8335 // e.g., "%vqsubq_v.i15 = call noundef <16 x i8>
8336 // @llvm.aarch64.neon.uqsub.v16i8(<16 x i8> %vext21.i,
8337 // <16 x i8> splat (i8 1)), !dbg !66"
8338 errs() << "QQQ:" << Prefix << " " << I << "\n";
8339 }
8340
8341 void visitResumeInst(ResumeInst &I) {
8342 LLVM_DEBUG(dbgs() << "Resume: " << I << "\n");
8343 // Nothing to do here.
8344 }
8345
8346 void visitCleanupReturnInst(CleanupReturnInst &CRI) {
8347 LLVM_DEBUG(dbgs() << "CleanupReturn: " << CRI << "\n");
8348 // Nothing to do here.
8349 }
8350
8351 void visitCatchReturnInst(CatchReturnInst &CRI) {
8352 LLVM_DEBUG(dbgs() << "CatchReturn: " << CRI << "\n");
8353 // Nothing to do here.
8354 }
8355
8356 void instrumentAsmArgument(Value *Operand, Type *ElemTy, Instruction &I,
8357 IRBuilder<> &IRB, const DataLayout &DL,
8358 bool isOutput) {
8359 // For each assembly argument, we check its value for being initialized.
8360 // If the argument is a pointer, we assume it points to a single element
8361 // of the corresponding type (or to a 8-byte word, if the type is unsized).
8362 // Each such pointer is instrumented with a call to the runtime library.
8363 Type *OpType = Operand->getType();
8364 // Check the operand value itself.
8365 insertCheckShadowOf(Operand, &I);
8366 if (!OpType->isPointerTy() || !isOutput) {
8367 assert(!isOutput);
8368 return;
8369 }
8370 if (!ElemTy->isSized())
8371 return;
8372 // There is no shadow to unpoison for memory in other address spaces.
8373 if (isUntrackedAddrSpace(Operand))
8374 return;
8375 // ElemTy, derived from elementtype(), does not encode the alignment of
8376 // the pointer.
8377 Value *SizeVal =
8378 IRB.CreateTypeSize(MS.IntptrTy, DL.getTypeStoreSize(ElemTy));
8379 unpoisonMemoryRange(IRB, Operand, SizeVal, MS.MsanInstrumentAsmStoreFn,
8380 ElemTy);
8381 }
8382
8383 /// Get the number of output arguments returned by pointers.
8384 int getNumOutputArgs(InlineAsm *IA, CallBase *CB) {
8385 int NumRetOutputs = 0;
8386 int NumOutputs = 0;
8387 Type *RetTy = cast<Value>(CB)->getType();
8388 if (!RetTy->isVoidTy()) {
8389 // Register outputs are returned via the CallInst return value.
8390 auto *ST = dyn_cast<StructType>(RetTy);
8391 if (ST)
8392 NumRetOutputs = ST->getNumElements();
8393 else
8394 NumRetOutputs = 1;
8395 }
8396 InlineAsm::ConstraintInfoVector Constraints = IA->ParseConstraints();
8397 for (const InlineAsm::ConstraintInfo &Info : Constraints) {
8398 switch (Info.Type) {
8400 NumOutputs++;
8401 break;
8402 default:
8403 break;
8404 }
8405 }
8406 return NumOutputs - NumRetOutputs;
8407 }
8408
8409 void visitAsmInstruction(Instruction &I) {
8410 // Conservative inline assembly handling: check for poisoned shadow of
8411 // asm() arguments, then unpoison the result and all the memory locations
8412 // pointed to by those arguments.
8413 // An inline asm() statement in C++ contains lists of input and output
8414 // arguments used by the assembly code. These are mapped to operands of the
8415 // CallInst as follows:
8416 // - nR register outputs ("=r) are returned by value in a single structure
8417 // (SSA value of the CallInst);
8418 // - nO other outputs ("=m" and others) are returned by pointer as first
8419 // nO operands of the CallInst;
8420 // - nI inputs ("r", "m" and others) are passed to CallInst as the
8421 // remaining nI operands.
8422 // The total number of asm() arguments in the source is nR+nO+nI, and the
8423 // corresponding CallInst has nO+nI+1 operands (the last operand is the
8424 // function to be called).
8425 const DataLayout &DL = F.getDataLayout();
8426 CallBase *CB = cast<CallBase>(&I);
8427 IRBuilder<> IRB(&I);
8428 InlineAsm *IA = cast<InlineAsm>(CB->getCalledOperand());
8429 int OutputArgs = getNumOutputArgs(IA, CB);
8430 // The last operand of a CallInst is the function itself.
8431 int NumOperands = CB->getNumOperands() - 1;
8432
8433 // Check input arguments. Doing so before unpoisoning output arguments, so
8434 // that we won't overwrite uninit values before checking them.
8435 for (int i = OutputArgs; i < NumOperands; i++) {
8436 Value *Operand = CB->getOperand(i);
8437 instrumentAsmArgument(Operand, CB->getParamElementType(i), I, IRB, DL,
8438 /*isOutput*/ false);
8439 }
8440 // Unpoison output arguments. This must happen before the actual InlineAsm
8441 // call, so that the shadow for memory published in the asm() statement
8442 // remains valid.
8443 for (int i = 0; i < OutputArgs; i++) {
8444 Value *Operand = CB->getOperand(i);
8445 instrumentAsmArgument(Operand, CB->getParamElementType(i), I, IRB, DL,
8446 /*isOutput*/ true);
8447 }
8448
8449 setShadow(&I, getCleanShadow(&I));
8450 setOrigin(&I, getCleanOrigin());
8451 }
8452
8453 void visitFreezeInst(FreezeInst &I) {
8454 // Freeze always returns a fully defined value.
8455 setShadow(&I, getCleanShadow(&I));
8456 setOrigin(&I, getCleanOrigin());
8457 }
8458
8459 void visitInstruction(Instruction &I) {
8460 // Everything else: stop propagating and check for poisoned shadow.
8461 if (Opts.msan_dump_strict_instructions)
8462 dumpInst(I, "Strict");
8463 LLVM_DEBUG(dbgs() << "DEFAULT: " << I << "\n");
8464 for (size_t i = 0, n = I.getNumOperands(); i < n; i++) {
8465 Value *Operand = I.getOperand(i);
8466 if (Operand->getType()->isSized())
8467 insertCheckShadowOf(Operand, &I);
8468 }
8469 setShadow(&I, getCleanShadow(&I));
8470 setOrigin(&I, getCleanOrigin());
8471 }
8472};
8473
8474struct VarArgHelperBase : public VarArgHelper {
8475 Function &F;
8476 MemorySanitizer &MS;
8477 MemorySanitizerVisitor &MSV;
8478 SmallVector<CallInst *, 16> VAStartInstrumentationList;
8479 const unsigned VAListTagSize;
8480
8481 VarArgHelperBase(Function &F, MemorySanitizer &MS,
8482 MemorySanitizerVisitor &MSV, unsigned VAListTagSize)
8483 : F(F), MS(MS), MSV(MSV), VAListTagSize(VAListTagSize) {}
8484
8485 Value *getShadowAddrForVAArgument(IRBuilder<> &IRB, unsigned ArgOffset) {
8486 Value *Base = IRB.CreatePointerCast(MS.VAArgTLS, MS.IntptrTy);
8487 return IRB.CreateAdd(Base, ConstantInt::get(MS.IntptrTy, ArgOffset));
8488 }
8489
8490 /// Compute the shadow address for a given va_arg.
8491 Value *getShadowPtrForVAArgument(IRBuilder<> &IRB, unsigned ArgOffset) {
8492 return IRB.CreatePtrAddWithUnsignedOffset(MS.VAArgTLS, ArgOffset,
8493 "_msarg_va_s");
8494 }
8495
8496 /// Compute the shadow address for a given va_arg.
8497 Value *getShadowPtrForVAArgument(IRBuilder<> &IRB, unsigned ArgOffset,
8498 unsigned ArgSize) {
8499 // Make sure we don't overflow __msan_va_arg_tls.
8500 if (ArgOffset + ArgSize > kParamTLSSize)
8501 return nullptr;
8502 return getShadowPtrForVAArgument(IRB, ArgOffset);
8503 }
8504
8505 /// Compute the origin address for a given va_arg.
8506 Value *getOriginPtrForVAArgument(IRBuilder<> &IRB, unsigned ArgOffset) {
8507 // getOriginPtrForVAArgument() is always called after
8508 // getShadowPtrForVAArgument(), so __msan_va_arg_origin_tls can never
8509 // overflow.
8510 return IRB.CreatePtrAddWithUnsignedOffset(MS.VAArgOriginTLS, ArgOffset,
8511 "_msarg_va_o");
8512 }
8513
8514 void CleanUnusedTLS(IRBuilder<> &IRB, Value *ShadowBase,
8515 unsigned BaseOffset) {
8516 // The tails of __msan_va_arg_tls is not large enough to fit full
8517 // value shadow, but it will be copied to backup anyway. Make it
8518 // clean.
8519 if (BaseOffset >= kParamTLSSize)
8520 return;
8521 Value *TailSize =
8522 ConstantInt::getSigned(IRB.getInt32Ty(), kParamTLSSize - BaseOffset);
8523 IRB.CreateMemSet(ShadowBase, ConstantInt::getNullValue(IRB.getInt8Ty()),
8524 TailSize, Align(8));
8525 }
8526
8527 void unpoisonVAListTagForInst(IntrinsicInst &I) {
8528 IRBuilder<> IRB(&I);
8529 Value *VAListTag = I.getArgOperand(0);
8530 const Align Alignment = Align(8);
8531 auto [ShadowPtr, OriginPtr] = MSV.getShadowOriginPtr(
8532 VAListTag, IRB, IRB.getInt8Ty(), Alignment, /*isStore*/ true);
8533 // Unpoison the whole __va_list_tag.
8534 IRB.CreateMemSet(ShadowPtr, Constant::getNullValue(IRB.getInt8Ty()),
8535 VAListTagSize, Alignment, false);
8536 }
8537
8538 void visitVAStartInst(VAStartInst &I) override {
8539 if (F.getCallingConv() == CallingConv::Win64)
8540 return;
8541 VAStartInstrumentationList.push_back(&I);
8542 unpoisonVAListTagForInst(I);
8543 }
8544
8545 void visitVACopyInst(VACopyInst &I) override {
8546 if (F.getCallingConv() == CallingConv::Win64)
8547 return;
8548 unpoisonVAListTagForInst(I);
8549 }
8550};
8551
8552class VarArgStackModelHelperBase : public VarArgHelperBase {
8553public:
8554 VarArgStackModelHelperBase(Function &F, MemorySanitizer &MS,
8555 MemorySanitizerVisitor &MSV,
8556 unsigned VAListTagSize)
8557 : VarArgHelperBase(F, MS, MSV, VAListTagSize) {}
8558
8559 void finalizeInstrumentation() override {
8560 assert(!VAArgSize && !VAArgTLSCopy &&
8561 "finalizeInstrumentation called twice");
8562 IRBuilder<> IRB(MSV.FnPrologueEnd);
8563 VAArgSize = IRB.CreateLoad(MS.IntptrTy, MS.VAArgOverflowSizeTLS);
8564 Value *CopySize = VAArgSize;
8565
8566 if (!VAStartInstrumentationList.empty()) {
8567 // If there is a va_start in this function, make a backup copy of
8568 // va_arg_tls somewhere in the function entry block.
8569 VAArgTLSCopy = IRB.CreateAlloca(Type::getInt8Ty(*MS.C), CopySize);
8570 VAArgTLSCopy->setAlignment(kShadowTLSAlignment);
8571 IRB.CreateMemSet(VAArgTLSCopy, Constant::getNullValue(IRB.getInt8Ty()),
8572 CopySize, kShadowTLSAlignment, false);
8573
8574 Value *SrcSize = IRB.CreateBinaryIntrinsic(
8575 Intrinsic::umin, CopySize,
8576 ConstantInt::get(MS.IntptrTy, kParamTLSSize));
8577 IRB.CreateMemCpy(VAArgTLSCopy, kShadowTLSAlignment, MS.VAArgTLS,
8578 kShadowTLSAlignment, SrcSize);
8579 }
8580
8581 // Instrument va_start.
8582 // Copy va_list shadow from the backup copy of the TLS contents.
8583 for (CallInst *OrigInst : VAStartInstrumentationList) {
8584 NextNodeIRBuilder IRB(OrigInst);
8585 Value *VAListTag = OrigInst->getArgOperand(0);
8586 Value *RegSaveAreaPtrPtr = IRB.CreateIntToPtr(
8587 IRB.CreatePtrToInt(VAListTag, MS.IntptrTy), MS.PtrTy);
8588 Value *RegSaveAreaPtr = IRB.CreateLoad(MS.PtrTy, RegSaveAreaPtrPtr);
8589 Value *RegSaveAreaShadowPtr, *RegSaveAreaOriginPtr;
8590 const DataLayout &DL = F.getDataLayout();
8591 unsigned IntptrSize = DL.getTypeStoreSize(MS.IntptrTy);
8592 const Align Alignment = Align(IntptrSize);
8593 std::tie(RegSaveAreaShadowPtr, RegSaveAreaOriginPtr) =
8594 MSV.getShadowOriginPtr(RegSaveAreaPtr, IRB, IRB.getInt8Ty(),
8595 Alignment, /*isStore*/ true);
8596 IRB.CreateMemCpy(RegSaveAreaShadowPtr, Alignment, VAArgTLSCopy, Alignment,
8597 CopySize);
8598 }
8599 }
8600
8601private:
8602 AllocaInst *VAArgTLSCopy = nullptr;
8603 Value *VAArgSize = nullptr;
8604};
8605
8606/// AMD64-specific implementation of VarArgHelper.
8607struct VarArgAMD64Helper : public VarArgHelperBase {
8608 // An unfortunate workaround for asymmetric lowering of va_arg stuff.
8609 // See a comment in visitCallBase for more details.
8610 static const unsigned AMD64GpEndOffset = 48; // AMD64 ABI Draft 0.99.6 p3.5.7
8611 static const unsigned AMD64FpEndOffsetSSE = 176;
8612 // If SSE is disabled, fp_offset in va_list is zero.
8613 static const unsigned AMD64FpEndOffsetNoSSE = AMD64GpEndOffset;
8614
8615 unsigned AMD64FpEndOffset;
8616 AllocaInst *VAArgTLSCopy = nullptr;
8617 AllocaInst *VAArgTLSOriginCopy = nullptr;
8618 Value *VAArgOverflowSize = nullptr;
8619
8620 enum ArgKind { AK_GeneralPurpose, AK_FloatingPoint, AK_Memory };
8621
8622 VarArgAMD64Helper(Function &F, MemorySanitizer &MS,
8623 MemorySanitizerVisitor &MSV)
8624 : VarArgHelperBase(F, MS, MSV, /*VAListTagSize=*/24) {
8625 AMD64FpEndOffset = AMD64FpEndOffsetSSE;
8626 for (const auto &Attr : F.getAttributes().getFnAttrs()) {
8627 if (Attr.isStringAttribute() &&
8628 (Attr.getKindAsString() == "target-features")) {
8629 if (Attr.getValueAsString().contains("-sse"))
8630 AMD64FpEndOffset = AMD64FpEndOffsetNoSSE;
8631 break;
8632 }
8633 }
8634 }
8635
8636 ArgKind classifyArgument(Value *arg) {
8637 // A very rough approximation of X86_64 argument classification rules.
8638 Type *T = arg->getType();
8639 if (T->isX86_FP80Ty())
8640 return AK_Memory;
8641 if (T->isFPOrFPVectorTy())
8642 return AK_FloatingPoint;
8643 if (T->isIntegerTy() && T->getPrimitiveSizeInBits() <= 64)
8644 return AK_GeneralPurpose;
8645 if (T->isPointerTy())
8646 return AK_GeneralPurpose;
8647 return AK_Memory;
8648 }
8649
8650 // For VarArg functions, store the argument shadow in an ABI-specific format
8651 // that corresponds to va_list layout.
8652 // We do this because Clang lowers va_arg in the frontend, and this pass
8653 // only sees the low level code that deals with va_list internals.
8654 // A much easier alternative (provided that Clang emits va_arg instructions)
8655 // would have been to associate each live instance of va_list with a copy of
8656 // MSanParamTLS, and extract shadow on va_arg() call in the argument list
8657 // order.
8658 void visitCallBase(CallBase &CB, IRBuilder<> &IRB) override {
8659 unsigned GpOffset = 0;
8660 unsigned FpOffset = AMD64GpEndOffset;
8661 unsigned OverflowOffset = AMD64FpEndOffset;
8662 const DataLayout &DL = F.getDataLayout();
8663
8664 for (const auto &[ArgNo, A] : llvm::enumerate(CB.args())) {
8665 bool IsFixed = ArgNo < CB.getFunctionType()->getNumParams();
8666 bool IsByVal = CB.isByValArgument(ArgNo);
8667 if (IsByVal) {
8668 // ByVal arguments always go to the overflow area.
8669 // Fixed arguments passed through the overflow area will be stepped
8670 // over by va_start, so don't count them towards the offset.
8671 if (IsFixed)
8672 continue;
8673 assert(A->getType()->isPointerTy());
8674 Type *RealTy = CB.getParamByValType(ArgNo);
8675 uint64_t ArgSize = DL.getTypeAllocSize(RealTy);
8676 uint64_t AlignedSize = alignTo(ArgSize, 8);
8677 unsigned BaseOffset = OverflowOffset;
8678 Value *ShadowBase = getShadowPtrForVAArgument(IRB, OverflowOffset);
8679 Value *OriginBase = nullptr;
8680 if (MS.TrackOrigins)
8681 OriginBase = getOriginPtrForVAArgument(IRB, OverflowOffset);
8682 OverflowOffset += AlignedSize;
8683
8684 if (OverflowOffset > kParamTLSSize) {
8685 CleanUnusedTLS(IRB, ShadowBase, BaseOffset);
8686 continue; // We have no space to copy shadow there.
8687 }
8688
8689 Value *ShadowPtr, *OriginPtr;
8690 std::tie(ShadowPtr, OriginPtr) =
8691 MSV.getShadowOriginPtr(A, IRB, IRB.getInt8Ty(), kShadowTLSAlignment,
8692 /*isStore*/ false);
8693 IRB.CreateMemCpy(ShadowBase, kShadowTLSAlignment, ShadowPtr,
8694 kShadowTLSAlignment, ArgSize);
8695 if (MS.TrackOrigins)
8696 IRB.CreateMemCpy(OriginBase, kShadowTLSAlignment, OriginPtr,
8697 kShadowTLSAlignment, ArgSize);
8698 } else {
8699 ArgKind AK = classifyArgument(A);
8700 if (AK == AK_GeneralPurpose && GpOffset >= AMD64GpEndOffset)
8701 AK = AK_Memory;
8702 if (AK == AK_FloatingPoint && FpOffset >= AMD64FpEndOffset)
8703 AK = AK_Memory;
8704 Value *ShadowBase, *OriginBase = nullptr;
8705 switch (AK) {
8706 case AK_GeneralPurpose:
8707 ShadowBase = getShadowPtrForVAArgument(IRB, GpOffset);
8708 if (MS.TrackOrigins)
8709 OriginBase = getOriginPtrForVAArgument(IRB, GpOffset);
8710 GpOffset += 8;
8711 assert(GpOffset <= kParamTLSSize);
8712 break;
8713 case AK_FloatingPoint:
8714 ShadowBase = getShadowPtrForVAArgument(IRB, FpOffset);
8715 if (MS.TrackOrigins)
8716 OriginBase = getOriginPtrForVAArgument(IRB, FpOffset);
8717 FpOffset += 16;
8718 assert(FpOffset <= kParamTLSSize);
8719 break;
8720 case AK_Memory:
8721 if (IsFixed)
8722 continue;
8723 uint64_t ArgSize = DL.getTypeAllocSize(A->getType());
8724 uint64_t AlignedSize = alignTo(ArgSize, 8);
8725 unsigned BaseOffset = OverflowOffset;
8726 ShadowBase = getShadowPtrForVAArgument(IRB, OverflowOffset);
8727 if (MS.TrackOrigins) {
8728 OriginBase = getOriginPtrForVAArgument(IRB, OverflowOffset);
8729 }
8730 OverflowOffset += AlignedSize;
8731 if (OverflowOffset > kParamTLSSize) {
8732 // We have no space to copy shadow there.
8733 CleanUnusedTLS(IRB, ShadowBase, BaseOffset);
8734 continue;
8735 }
8736 }
8737 // Take fixed arguments into account for GpOffset and FpOffset,
8738 // but don't actually store shadows for them.
8739 // TODO(glider): don't call get*PtrForVAArgument() for them.
8740 if (IsFixed)
8741 continue;
8742 Value *Shadow = MSV.getShadow(A);
8743 IRB.CreateAlignedStore(Shadow, ShadowBase, kShadowTLSAlignment);
8744 if (MS.TrackOrigins) {
8745 Value *Origin = MSV.getOrigin(A);
8746 TypeSize StoreSize = DL.getTypeStoreSize(Shadow->getType());
8747 MSV.paintOrigin(IRB, Origin, OriginBase, StoreSize,
8749 }
8750 }
8751 }
8752 Constant *OverflowSize =
8753 ConstantInt::get(IRB.getInt64Ty(), OverflowOffset - AMD64FpEndOffset);
8754 IRB.CreateStore(OverflowSize, MS.VAArgOverflowSizeTLS);
8755 }
8756
8757 void finalizeInstrumentation() override {
8758 assert(!VAArgOverflowSize && !VAArgTLSCopy &&
8759 "finalizeInstrumentation called twice");
8760 if (!VAStartInstrumentationList.empty()) {
8761 // If there is a va_start in this function, make a backup copy of
8762 // va_arg_tls somewhere in the function entry block.
8763 IRBuilder<> IRB(MSV.FnPrologueEnd);
8764 VAArgOverflowSize =
8765 IRB.CreateLoad(IRB.getInt64Ty(), MS.VAArgOverflowSizeTLS);
8766 Value *CopySize = IRB.CreateAdd(
8767 ConstantInt::get(MS.IntptrTy, AMD64FpEndOffset), VAArgOverflowSize);
8768 VAArgTLSCopy = IRB.CreateAlloca(Type::getInt8Ty(*MS.C), CopySize);
8769 VAArgTLSCopy->setAlignment(kShadowTLSAlignment);
8770 IRB.CreateMemSet(VAArgTLSCopy, Constant::getNullValue(IRB.getInt8Ty()),
8771 CopySize, kShadowTLSAlignment, false);
8772
8773 Value *SrcSize = IRB.CreateBinaryIntrinsic(
8774 Intrinsic::umin, CopySize,
8775 ConstantInt::get(MS.IntptrTy, kParamTLSSize));
8776 IRB.CreateMemCpy(VAArgTLSCopy, kShadowTLSAlignment, MS.VAArgTLS,
8777 kShadowTLSAlignment, SrcSize);
8778 if (MS.TrackOrigins) {
8779 VAArgTLSOriginCopy = IRB.CreateAlloca(Type::getInt8Ty(*MS.C), CopySize);
8780 VAArgTLSOriginCopy->setAlignment(kShadowTLSAlignment);
8781 IRB.CreateMemCpy(VAArgTLSOriginCopy, kShadowTLSAlignment,
8782 MS.VAArgOriginTLS, kShadowTLSAlignment, SrcSize);
8783 }
8784 }
8785
8786 // Instrument va_start.
8787 // Copy va_list shadow from the backup copy of the TLS contents.
8788 for (CallInst *OrigInst : VAStartInstrumentationList) {
8789 NextNodeIRBuilder IRB(OrigInst);
8790 Value *VAListTag = OrigInst->getArgOperand(0);
8791
8792 Value *RegSaveAreaPtrPtr =
8793 IRB.CreatePtrAddWithUnsignedOffset(VAListTag, 16);
8794 Value *RegSaveAreaPtr = IRB.CreateLoad(MS.PtrTy, RegSaveAreaPtrPtr);
8795 Value *RegSaveAreaShadowPtr, *RegSaveAreaOriginPtr;
8796 const Align Alignment = Align(16);
8797 std::tie(RegSaveAreaShadowPtr, RegSaveAreaOriginPtr) =
8798 MSV.getShadowOriginPtr(RegSaveAreaPtr, IRB, IRB.getInt8Ty(),
8799 Alignment, /*isStore*/ true);
8800 IRB.CreateMemCpy(RegSaveAreaShadowPtr, Alignment, VAArgTLSCopy, Alignment,
8801 AMD64FpEndOffset);
8802 if (MS.TrackOrigins)
8803 IRB.CreateMemCpy(RegSaveAreaOriginPtr, Alignment, VAArgTLSOriginCopy,
8804 Alignment, AMD64FpEndOffset);
8805 Value *OverflowArgAreaPtrPtr =
8806 IRB.CreatePtrAddWithUnsignedOffset(VAListTag, 8);
8807 Value *OverflowArgAreaPtr =
8808 IRB.CreateLoad(MS.PtrTy, OverflowArgAreaPtrPtr);
8809 Value *OverflowArgAreaShadowPtr, *OverflowArgAreaOriginPtr;
8810 std::tie(OverflowArgAreaShadowPtr, OverflowArgAreaOriginPtr) =
8811 MSV.getShadowOriginPtr(OverflowArgAreaPtr, IRB, IRB.getInt8Ty(),
8812 Alignment, /*isStore*/ true);
8813 Value *SrcPtr = IRB.CreateConstGEP1_32(IRB.getInt8Ty(), VAArgTLSCopy,
8814 AMD64FpEndOffset);
8815 IRB.CreateMemCpy(OverflowArgAreaShadowPtr, Alignment, SrcPtr, Alignment,
8816 VAArgOverflowSize);
8817 if (MS.TrackOrigins) {
8818 SrcPtr = IRB.CreateConstGEP1_32(IRB.getInt8Ty(), VAArgTLSOriginCopy,
8819 AMD64FpEndOffset);
8820 IRB.CreateMemCpy(OverflowArgAreaOriginPtr, Alignment, SrcPtr, Alignment,
8821 VAArgOverflowSize);
8822 }
8823 }
8824 }
8825};
8826
8827/// AArch64-specific implementation of VarArgHelper.
8828struct VarArgAArch64Helper : public VarArgHelperBase {
8829 static const unsigned kAArch64GrArgSize = 64;
8830 static const unsigned kAArch64VrArgSize = 128;
8831
8832 static const unsigned AArch64GrBegOffset = 0;
8833 static const unsigned AArch64GrEndOffset = kAArch64GrArgSize;
8834 // Make VR space aligned to 16 bytes.
8835 static const unsigned AArch64VrBegOffset = AArch64GrEndOffset;
8836 static const unsigned AArch64VrEndOffset =
8837 AArch64VrBegOffset + kAArch64VrArgSize;
8838 static const unsigned AArch64VAEndOffset = AArch64VrEndOffset;
8839
8840 AllocaInst *VAArgTLSCopy = nullptr;
8841 Value *VAArgOverflowSize = nullptr;
8842
8843 enum ArgKind { AK_GeneralPurpose, AK_FloatingPoint, AK_Memory };
8844
8845 VarArgAArch64Helper(Function &F, MemorySanitizer &MS,
8846 MemorySanitizerVisitor &MSV)
8847 : VarArgHelperBase(F, MS, MSV, /*VAListTagSize=*/32) {}
8848
8849 // A very rough approximation of aarch64 argument classification rules.
8850 std::pair<ArgKind, uint64_t> classifyArgument(Type *T) {
8851 if (T->isIntOrPtrTy() && T->getPrimitiveSizeInBits() <= 64)
8852 return {AK_GeneralPurpose, 1};
8853 if (T->isFloatingPointTy() && T->getPrimitiveSizeInBits() <= 128)
8854 return {AK_FloatingPoint, 1};
8855
8856 if (T->isArrayTy()) {
8857 auto R = classifyArgument(T->getArrayElementType());
8858 R.second *= T->getScalarType()->getArrayNumElements();
8859 return R;
8860 }
8861
8862 if (const FixedVectorType *FV = dyn_cast<FixedVectorType>(T)) {
8863 auto R = classifyArgument(FV->getScalarType());
8864 R.second *= FV->getNumElements();
8865 return R;
8866 }
8867
8868 LLVM_DEBUG(errs() << "Unknown vararg type: " << *T << "\n");
8869 return {AK_Memory, 0};
8870 }
8871
8872 // The instrumentation stores the argument shadow in a non ABI-specific
8873 // format because it does not know which argument is named (since Clang,
8874 // like x86_64 case, lowers the va_args in the frontend and this pass only
8875 // sees the low level code that deals with va_list internals).
8876 // The first seven GR registers are saved in the first 56 bytes of the
8877 // va_arg tls arra, followed by the first 8 FP/SIMD registers, and then
8878 // the remaining arguments.
8879 // Using constant offset within the va_arg TLS array allows fast copy
8880 // in the finalize instrumentation.
8881 void visitCallBase(CallBase &CB, IRBuilder<> &IRB) override {
8882 unsigned GrOffset = AArch64GrBegOffset;
8883 unsigned VrOffset = AArch64VrBegOffset;
8884 unsigned OverflowOffset = AArch64VAEndOffset;
8885
8886 const DataLayout &DL = F.getDataLayout();
8887 for (const auto &[ArgNo, A] : llvm::enumerate(CB.args())) {
8888 bool IsFixed = ArgNo < CB.getFunctionType()->getNumParams();
8889 auto [AK, RegNum] = classifyArgument(A->getType());
8890 if (AK == AK_GeneralPurpose &&
8891 (GrOffset + RegNum * 8) > AArch64GrEndOffset)
8892 AK = AK_Memory;
8893 if (AK == AK_FloatingPoint &&
8894 (VrOffset + RegNum * 16) > AArch64VrEndOffset)
8895 AK = AK_Memory;
8896 Value *Base;
8897 switch (AK) {
8898 case AK_GeneralPurpose:
8899 Base = getShadowPtrForVAArgument(IRB, GrOffset);
8900 GrOffset += 8 * RegNum;
8901 break;
8902 case AK_FloatingPoint:
8903 Base = getShadowPtrForVAArgument(IRB, VrOffset);
8904 VrOffset += 16 * RegNum;
8905 break;
8906 case AK_Memory:
8907 // Don't count fixed arguments in the overflow area - va_start will
8908 // skip right over them.
8909 if (IsFixed)
8910 continue;
8911 uint64_t ArgSize = DL.getTypeAllocSize(A->getType());
8912 uint64_t AlignedSize = alignTo(ArgSize, 8);
8913 unsigned BaseOffset = OverflowOffset;
8914 Base = getShadowPtrForVAArgument(IRB, BaseOffset);
8915 OverflowOffset += AlignedSize;
8916 if (OverflowOffset > kParamTLSSize) {
8917 // We have no space to copy shadow there.
8918 CleanUnusedTLS(IRB, Base, BaseOffset);
8919 continue;
8920 }
8921 break;
8922 }
8923 // Count Gp/Vr fixed arguments to their respective offsets, but don't
8924 // bother to actually store a shadow.
8925 if (IsFixed)
8926 continue;
8927 IRB.CreateAlignedStore(MSV.getShadow(A), Base, kShadowTLSAlignment);
8928 }
8929 Constant *OverflowSize =
8930 ConstantInt::get(IRB.getInt64Ty(), OverflowOffset - AArch64VAEndOffset);
8931 IRB.CreateStore(OverflowSize, MS.VAArgOverflowSizeTLS);
8932 }
8933
8934 // Retrieve a va_list field of 'void*' size.
8935 Value *getVAField64(IRBuilder<> &IRB, Value *VAListTag, unsigned Offset) {
8936 Value *SaveAreaPtrPtr =
8937 IRB.CreatePtrAddWithUnsignedOffset(VAListTag, Offset);
8938 return IRB.CreateLoad(Type::getInt64Ty(*MS.C), SaveAreaPtrPtr);
8939 }
8940
8941 // Retrieve a va_list field of 'int' size.
8942 Value *getVAField32(IRBuilder<> &IRB, Value *VAListTag, unsigned Offset) {
8943 Value *SaveAreaPtr = IRB.CreatePtrAddWithUnsignedOffset(VAListTag, Offset);
8944 Value *SaveArea32 = IRB.CreateLoad(IRB.getInt32Ty(), SaveAreaPtr);
8945 return IRB.CreateSExt(SaveArea32, MS.IntptrTy);
8946 }
8947
8948 void finalizeInstrumentation() override {
8949 assert(!VAArgOverflowSize && !VAArgTLSCopy &&
8950 "finalizeInstrumentation called twice");
8951 if (!VAStartInstrumentationList.empty()) {
8952 // If there is a va_start in this function, make a backup copy of
8953 // va_arg_tls somewhere in the function entry block.
8954 IRBuilder<> IRB(MSV.FnPrologueEnd);
8955 VAArgOverflowSize =
8956 IRB.CreateLoad(IRB.getInt64Ty(), MS.VAArgOverflowSizeTLS);
8957 Value *CopySize = IRB.CreateAdd(
8958 ConstantInt::get(MS.IntptrTy, AArch64VAEndOffset), VAArgOverflowSize);
8959 VAArgTLSCopy = IRB.CreateAlloca(Type::getInt8Ty(*MS.C), CopySize);
8960 VAArgTLSCopy->setAlignment(kShadowTLSAlignment);
8961 IRB.CreateMemSet(VAArgTLSCopy, Constant::getNullValue(IRB.getInt8Ty()),
8962 CopySize, kShadowTLSAlignment, false);
8963
8964 Value *SrcSize = IRB.CreateBinaryIntrinsic(
8965 Intrinsic::umin, CopySize,
8966 ConstantInt::get(MS.IntptrTy, kParamTLSSize));
8967 IRB.CreateMemCpy(VAArgTLSCopy, kShadowTLSAlignment, MS.VAArgTLS,
8968 kShadowTLSAlignment, SrcSize);
8969 }
8970
8971 Value *GrArgSize = ConstantInt::get(MS.IntptrTy, kAArch64GrArgSize);
8972 Value *VrArgSize = ConstantInt::get(MS.IntptrTy, kAArch64VrArgSize);
8973
8974 // Instrument va_start, copy va_list shadow from the backup copy of
8975 // the TLS contents.
8976 for (CallInst *OrigInst : VAStartInstrumentationList) {
8977 NextNodeIRBuilder IRB(OrigInst);
8978
8979 Value *VAListTag = OrigInst->getArgOperand(0);
8980
8981 // The variadic ABI for AArch64 creates two areas to save the incoming
8982 // argument registers (one for 64-bit general register xn-x7 and another
8983 // for 128-bit FP/SIMD vn-v7).
8984 // We need then to propagate the shadow arguments on both regions
8985 // 'va::__gr_top + va::__gr_offs' and 'va::__vr_top + va::__vr_offs'.
8986 // The remaining arguments are saved on shadow for 'va::stack'.
8987 // One caveat is it requires only to propagate the non-named arguments,
8988 // however on the call site instrumentation 'all' the arguments are
8989 // saved. So to copy the shadow values from the va_arg TLS array
8990 // we need to adjust the offset for both GR and VR fields based on
8991 // the __{gr,vr}_offs value (since they are stores based on incoming
8992 // named arguments).
8993 Type *RegSaveAreaPtrTy = IRB.getPtrTy();
8994
8995 // Read the stack pointer from the va_list.
8996 Value *StackSaveAreaPtr =
8997 IRB.CreateIntToPtr(getVAField64(IRB, VAListTag, 0), RegSaveAreaPtrTy);
8998
8999 // Read both the __gr_top and __gr_off and add them up.
9000 Value *GrTopSaveAreaPtr = getVAField64(IRB, VAListTag, 8);
9001 Value *GrOffSaveArea = getVAField32(IRB, VAListTag, 24);
9002
9003 Value *GrRegSaveAreaPtr = IRB.CreateIntToPtr(
9004 IRB.CreateAdd(GrTopSaveAreaPtr, GrOffSaveArea), RegSaveAreaPtrTy);
9005
9006 // Read both the __vr_top and __vr_off and add them up.
9007 Value *VrTopSaveAreaPtr = getVAField64(IRB, VAListTag, 16);
9008 Value *VrOffSaveArea = getVAField32(IRB, VAListTag, 28);
9009
9010 Value *VrRegSaveAreaPtr = IRB.CreateIntToPtr(
9011 IRB.CreateAdd(VrTopSaveAreaPtr, VrOffSaveArea), RegSaveAreaPtrTy);
9012
9013 // It does not know how many named arguments is being used and, on the
9014 // callsite all the arguments were saved. Since __gr_off is defined as
9015 // '0 - ((8 - named_gr) * 8)', the idea is to just propagate the variadic
9016 // argument by ignoring the bytes of shadow from named arguments.
9017 Value *GrRegSaveAreaShadowPtrOff =
9018 IRB.CreateAdd(GrArgSize, GrOffSaveArea);
9019
9020 Value *GrRegSaveAreaShadowPtr =
9021 MSV.getShadowOriginPtr(GrRegSaveAreaPtr, IRB, IRB.getInt8Ty(),
9022 Align(8), /*isStore*/ true)
9023 .first;
9024
9025 Value *GrSrcPtr =
9026 IRB.CreateInBoundsPtrAdd(VAArgTLSCopy, GrRegSaveAreaShadowPtrOff);
9027 Value *GrCopySize = IRB.CreateSub(GrArgSize, GrRegSaveAreaShadowPtrOff);
9028
9029 IRB.CreateMemCpy(GrRegSaveAreaShadowPtr, Align(8), GrSrcPtr, Align(8),
9030 GrCopySize);
9031
9032 // Again, but for FP/SIMD values.
9033 Value *VrRegSaveAreaShadowPtrOff =
9034 IRB.CreateAdd(VrArgSize, VrOffSaveArea);
9035
9036 Value *VrRegSaveAreaShadowPtr =
9037 MSV.getShadowOriginPtr(VrRegSaveAreaPtr, IRB, IRB.getInt8Ty(),
9038 Align(8), /*isStore*/ true)
9039 .first;
9040
9041 Value *VrSrcPtr = IRB.CreateInBoundsPtrAdd(
9042 IRB.CreatePtrAddWithUnsignedOffset(VAArgTLSCopy, AArch64VrBegOffset,
9044 VrRegSaveAreaShadowPtrOff);
9045 Value *VrCopySize = IRB.CreateSub(VrArgSize, VrRegSaveAreaShadowPtrOff);
9046
9047 IRB.CreateMemCpy(VrRegSaveAreaShadowPtr, Align(8), VrSrcPtr, Align(8),
9048 VrCopySize);
9049
9050 // And finally for remaining arguments.
9051 Value *StackSaveAreaShadowPtr =
9052 MSV.getShadowOriginPtr(StackSaveAreaPtr, IRB, IRB.getInt8Ty(),
9053 Align(16), /*isStore*/ true)
9054 .first;
9055
9056 Value *StackSrcPtr = IRB.CreatePtrAddWithUnsignedOffset(
9057 VAArgTLSCopy, AArch64VAEndOffset, "", GEPNoWrapFlags::inBounds());
9058
9059 IRB.CreateMemCpy(StackSaveAreaShadowPtr, Align(16), StackSrcPtr,
9060 Align(16), VAArgOverflowSize);
9061 }
9062 }
9063};
9064
9065/// PowerPC64-specific implementation of VarArgHelper.
9066struct VarArgPowerPC64Helper : public VarArgStackModelHelperBase {
9067 VarArgPowerPC64Helper(Function &F, MemorySanitizer &MS,
9068 MemorySanitizerVisitor &MSV)
9069 : VarArgStackModelHelperBase(F, MS, MSV, /*VAListTagSize=*/8) {}
9070
9071 void visitCallBase(CallBase &CB, IRBuilder<> &IRB) override {
9072 // For PowerPC, we need to deal with alignment of stack arguments -
9073 // they are mostly aligned to 8 bytes, but vectors and i128 arrays
9074 // are aligned to 16 bytes, byvals can be aligned to 8 or 16 bytes,
9075 // For that reason, we compute current offset from stack pointer (which is
9076 // always properly aligned), and offset for the first vararg, then subtract
9077 // them.
9078 unsigned VAArgBase;
9079 Triple TargetTriple(F.getParent()->getTargetTriple());
9080 // Parameter save area starts at 48 bytes from frame pointer for ABIv1,
9081 // and 32 bytes for ABIv2. This is usually determined by target
9082 // endianness, but in theory could be overridden by function attribute.
9083 if (TargetTriple.isPPC64ELFv2ABI())
9084 VAArgBase = 32;
9085 else
9086 VAArgBase = 48;
9087 unsigned VAArgOffset = VAArgBase;
9088 const DataLayout &DL = F.getDataLayout();
9089 for (const auto &[ArgNo, A] : llvm::enumerate(CB.args())) {
9090 bool IsFixed = ArgNo < CB.getFunctionType()->getNumParams();
9091 bool IsByVal = CB.isByValArgument(ArgNo);
9092 if (IsByVal) {
9093 assert(A->getType()->isPointerTy());
9094 Type *RealTy = CB.getParamByValType(ArgNo);
9095 uint64_t ArgSize = DL.getTypeAllocSize(RealTy);
9096 Align ArgAlign = CB.getParamAlign(ArgNo).value_or(Align(8));
9097 if (ArgAlign < 8)
9098 ArgAlign = Align(8);
9099 VAArgOffset = alignTo(VAArgOffset, ArgAlign);
9100 if (!IsFixed) {
9101 Value *Base =
9102 getShadowPtrForVAArgument(IRB, VAArgOffset - VAArgBase, ArgSize);
9103 if (Base) {
9104 Value *AShadowPtr, *AOriginPtr;
9105 std::tie(AShadowPtr, AOriginPtr) =
9106 MSV.getShadowOriginPtr(A, IRB, IRB.getInt8Ty(),
9107 kShadowTLSAlignment, /*isStore*/ false);
9108
9109 IRB.CreateMemCpy(Base, kShadowTLSAlignment, AShadowPtr,
9110 kShadowTLSAlignment, ArgSize);
9111 }
9112 }
9113 VAArgOffset += alignTo(ArgSize, Align(8));
9114 } else {
9115 Value *Base;
9116 uint64_t ArgSize = DL.getTypeAllocSize(A->getType());
9117 Align ArgAlign = Align(8);
9118 if (A->getType()->isArrayTy()) {
9119 // Arrays are aligned to element size, except for long double
9120 // arrays, which are aligned to 8 bytes.
9121 Type *ElementTy = A->getType()->getArrayElementType();
9122 if (!ElementTy->isPPC_FP128Ty())
9123 ArgAlign = Align(DL.getTypeAllocSize(ElementTy));
9124 } else if (A->getType()->isVectorTy()) {
9125 // Vectors are naturally aligned.
9126 ArgAlign = Align(ArgSize);
9127 }
9128 if (ArgAlign < 8)
9129 ArgAlign = Align(8);
9130 VAArgOffset = alignTo(VAArgOffset, ArgAlign);
9131 if (DL.isBigEndian()) {
9132 // Adjusting the shadow for argument with size < 8 to match the
9133 // placement of bits in big endian system
9134 if (ArgSize < 8)
9135 VAArgOffset += (8 - ArgSize);
9136 }
9137 if (!IsFixed) {
9138 Base =
9139 getShadowPtrForVAArgument(IRB, VAArgOffset - VAArgBase, ArgSize);
9140 if (Base)
9141 IRB.CreateAlignedStore(MSV.getShadow(A), Base, kShadowTLSAlignment);
9142 }
9143 VAArgOffset += ArgSize;
9144 VAArgOffset = alignTo(VAArgOffset, Align(8));
9145 }
9146 if (IsFixed)
9147 VAArgBase = VAArgOffset;
9148 }
9149
9150 Constant *TotalVAArgSize =
9151 ConstantInt::get(MS.IntptrTy, VAArgOffset - VAArgBase);
9152 // Here using VAArgOverflowSizeTLS as VAArgSizeTLS to avoid creation of
9153 // a new class member i.e. it is the total size of all VarArgs.
9154 IRB.CreateStore(TotalVAArgSize, MS.VAArgOverflowSizeTLS);
9155 }
9156};
9157
9158/// PowerPC32-specific implementation of VarArgHelper.
9159struct VarArgPowerPC32Helper : public VarArgHelperBase {
9160 AllocaInst *VAArgTLSCopy = nullptr;
9161 Value *VAArgSize = nullptr;
9162
9163 VarArgPowerPC32Helper(Function &F, MemorySanitizer &MS,
9164 MemorySanitizerVisitor &MSV)
9165 : VarArgHelperBase(F, MS, MSV, /*VAListTagSize=*/12) {}
9166
9167 void visitCallBase(CallBase &CB, IRBuilder<> &IRB) override {
9168 unsigned VAArgBase;
9169 // Parameter save area is 8 bytes from frame pointer in PPC32
9170 VAArgBase = 8;
9171 unsigned VAArgOffset = VAArgBase;
9172 const DataLayout &DL = F.getDataLayout();
9173 unsigned IntptrSize = DL.getTypeStoreSize(MS.IntptrTy);
9174 for (const auto &[ArgNo, A] : llvm::enumerate(CB.args())) {
9175 bool IsFixed = ArgNo < CB.getFunctionType()->getNumParams();
9176 bool IsByVal = CB.isByValArgument(ArgNo);
9177 if (IsByVal) {
9178 assert(A->getType()->isPointerTy());
9179 Type *RealTy = CB.getParamByValType(ArgNo);
9180 uint64_t ArgSize = DL.getTypeAllocSize(RealTy);
9181 Align ArgAlign = CB.getParamAlign(ArgNo).value_or(Align(IntptrSize));
9182 if (ArgAlign < IntptrSize)
9183 ArgAlign = Align(IntptrSize);
9184 VAArgOffset = alignTo(VAArgOffset, ArgAlign);
9185 if (!IsFixed) {
9186 Value *Base =
9187 getShadowPtrForVAArgument(IRB, VAArgOffset - VAArgBase, ArgSize);
9188 if (Base) {
9189 Value *AShadowPtr, *AOriginPtr;
9190 std::tie(AShadowPtr, AOriginPtr) =
9191 MSV.getShadowOriginPtr(A, IRB, IRB.getInt8Ty(),
9192 kShadowTLSAlignment, /*isStore*/ false);
9193
9194 IRB.CreateMemCpy(Base, kShadowTLSAlignment, AShadowPtr,
9195 kShadowTLSAlignment, ArgSize);
9196 }
9197 }
9198 VAArgOffset += alignTo(ArgSize, Align(IntptrSize));
9199 } else {
9200 Value *Base;
9201 Type *ArgTy = A->getType();
9202
9203 // On PPC 32 floating point variable arguments are stored in separate
9204 // area: fp_save_area = reg_save_area + 4*8. We do not copy shaodow for
9205 // them as they will be found when checking call arguments.
9206 if (!ArgTy->isFloatingPointTy()) {
9207 uint64_t ArgSize = DL.getTypeAllocSize(ArgTy);
9208 Align ArgAlign = Align(IntptrSize);
9209 if (ArgTy->isArrayTy()) {
9210 // Arrays are aligned to element size, except for long double
9211 // arrays, which are aligned to 8 bytes.
9212 Type *ElementTy = ArgTy->getArrayElementType();
9213 if (!ElementTy->isPPC_FP128Ty())
9214 ArgAlign = Align(DL.getTypeAllocSize(ElementTy));
9215 } else if (ArgTy->isVectorTy()) {
9216 // Vectors are naturally aligned.
9217 ArgAlign = Align(ArgSize);
9218 }
9219 if (ArgAlign < IntptrSize)
9220 ArgAlign = Align(IntptrSize);
9221 VAArgOffset = alignTo(VAArgOffset, ArgAlign);
9222 if (DL.isBigEndian()) {
9223 // Adjusting the shadow for argument with size < IntptrSize to match
9224 // the placement of bits in big endian system
9225 if (ArgSize < IntptrSize)
9226 VAArgOffset += (IntptrSize - ArgSize);
9227 }
9228 if (!IsFixed) {
9229 Base = getShadowPtrForVAArgument(IRB, VAArgOffset - VAArgBase,
9230 ArgSize);
9231 if (Base)
9232 IRB.CreateAlignedStore(MSV.getShadow(A), Base,
9234 }
9235 VAArgOffset += ArgSize;
9236 VAArgOffset = alignTo(VAArgOffset, Align(IntptrSize));
9237 }
9238 }
9239 }
9240
9241 Constant *TotalVAArgSize =
9242 ConstantInt::get(MS.IntptrTy, VAArgOffset - VAArgBase);
9243 // Here using VAArgOverflowSizeTLS as VAArgSizeTLS to avoid creation of
9244 // a new class member i.e. it is the total size of all VarArgs.
9245 IRB.CreateStore(TotalVAArgSize, MS.VAArgOverflowSizeTLS);
9246 }
9247
9248 void finalizeInstrumentation() override {
9249 assert(!VAArgSize && !VAArgTLSCopy &&
9250 "finalizeInstrumentation called twice");
9251 IRBuilder<> IRB(MSV.FnPrologueEnd);
9252 VAArgSize = IRB.CreateLoad(MS.IntptrTy, MS.VAArgOverflowSizeTLS);
9253 Value *CopySize = VAArgSize;
9254
9255 if (!VAStartInstrumentationList.empty()) {
9256 // If there is a va_start in this function, make a backup copy of
9257 // va_arg_tls somewhere in the function entry block.
9258
9259 VAArgTLSCopy = IRB.CreateAlloca(Type::getInt8Ty(*MS.C), CopySize);
9260 VAArgTLSCopy->setAlignment(kShadowTLSAlignment);
9261 IRB.CreateMemSet(VAArgTLSCopy, Constant::getNullValue(IRB.getInt8Ty()),
9262 CopySize, kShadowTLSAlignment, false);
9263
9264 Value *SrcSize = IRB.CreateBinaryIntrinsic(
9265 Intrinsic::umin, CopySize,
9266 ConstantInt::get(MS.IntptrTy, kParamTLSSize));
9267 IRB.CreateMemCpy(VAArgTLSCopy, kShadowTLSAlignment, MS.VAArgTLS,
9268 kShadowTLSAlignment, SrcSize);
9269 }
9270
9271 // Instrument va_start.
9272 // Copy va_list shadow from the backup copy of the TLS contents.
9273 for (CallInst *OrigInst : VAStartInstrumentationList) {
9274 NextNodeIRBuilder IRB(OrigInst);
9275 Value *VAListTag = OrigInst->getArgOperand(0);
9276 Value *RegSaveAreaPtrPtr = IRB.CreatePtrToInt(VAListTag, MS.IntptrTy);
9277 Value *RegSaveAreaSize = CopySize;
9278
9279 // In PPC32 va_list_tag is a struct
9280 RegSaveAreaPtrPtr =
9281 IRB.CreateAdd(RegSaveAreaPtrPtr, ConstantInt::get(MS.IntptrTy, 8));
9282
9283 // On PPC 32 reg_save_area can only hold 32 bytes of data
9284 RegSaveAreaSize = IRB.CreateBinaryIntrinsic(
9285 Intrinsic::umin, CopySize, ConstantInt::get(MS.IntptrTy, 32));
9286
9287 RegSaveAreaPtrPtr = IRB.CreateIntToPtr(RegSaveAreaPtrPtr, MS.PtrTy);
9288 Value *RegSaveAreaPtr = IRB.CreateLoad(MS.PtrTy, RegSaveAreaPtrPtr);
9289
9290 const DataLayout &DL = F.getDataLayout();
9291 unsigned IntptrSize = DL.getTypeStoreSize(MS.IntptrTy);
9292 const Align Alignment = Align(IntptrSize);
9293
9294 { // Copy reg save area
9295 Value *RegSaveAreaShadowPtr, *RegSaveAreaOriginPtr;
9296 std::tie(RegSaveAreaShadowPtr, RegSaveAreaOriginPtr) =
9297 MSV.getShadowOriginPtr(RegSaveAreaPtr, IRB, IRB.getInt8Ty(),
9298 Alignment, /*isStore*/ true);
9299 IRB.CreateMemCpy(RegSaveAreaShadowPtr, Alignment, VAArgTLSCopy,
9300 Alignment, RegSaveAreaSize);
9301
9302 RegSaveAreaShadowPtr =
9303 IRB.CreatePtrToInt(RegSaveAreaShadowPtr, MS.IntptrTy);
9304 Value *FPSaveArea = IRB.CreateAdd(RegSaveAreaShadowPtr,
9305 ConstantInt::get(MS.IntptrTy, 32));
9306 FPSaveArea = IRB.CreateIntToPtr(FPSaveArea, MS.PtrTy);
9307 // We fill fp shadow with zeroes as uninitialized fp args should have
9308 // been found during call base check
9309 IRB.CreateMemSet(FPSaveArea, ConstantInt::getNullValue(IRB.getInt8Ty()),
9310 ConstantInt::get(MS.IntptrTy, 32), Alignment);
9311 }
9312
9313 { // Copy overflow area
9314 // RegSaveAreaSize is min(CopySize, 32) -> no overflow can occur
9315 Value *OverflowAreaSize = IRB.CreateSub(CopySize, RegSaveAreaSize);
9316
9317 Value *OverflowAreaPtrPtr = IRB.CreatePtrToInt(VAListTag, MS.IntptrTy);
9318 OverflowAreaPtrPtr =
9319 IRB.CreateAdd(OverflowAreaPtrPtr, ConstantInt::get(MS.IntptrTy, 4));
9320 OverflowAreaPtrPtr = IRB.CreateIntToPtr(OverflowAreaPtrPtr, MS.PtrTy);
9321
9322 Value *OverflowAreaPtr = IRB.CreateLoad(MS.PtrTy, OverflowAreaPtrPtr);
9323
9324 Value *OverflowAreaShadowPtr, *OverflowAreaOriginPtr;
9325 std::tie(OverflowAreaShadowPtr, OverflowAreaOriginPtr) =
9326 MSV.getShadowOriginPtr(OverflowAreaPtr, IRB, IRB.getInt8Ty(),
9327 Alignment, /*isStore*/ true);
9328
9329 Value *OverflowVAArgTLSCopyPtr =
9330 IRB.CreatePtrToInt(VAArgTLSCopy, MS.IntptrTy);
9331 OverflowVAArgTLSCopyPtr =
9332 IRB.CreateAdd(OverflowVAArgTLSCopyPtr, RegSaveAreaSize);
9333
9334 OverflowVAArgTLSCopyPtr =
9335 IRB.CreateIntToPtr(OverflowVAArgTLSCopyPtr, MS.PtrTy);
9336 IRB.CreateMemCpy(OverflowAreaShadowPtr, Alignment,
9337 OverflowVAArgTLSCopyPtr, Alignment, OverflowAreaSize);
9338 }
9339 }
9340 }
9341};
9342
9343/// SystemZ-specific implementation of VarArgHelper.
9344struct VarArgSystemZHelper : public VarArgHelperBase {
9345 static const unsigned SystemZGpOffset = 16;
9346 static const unsigned SystemZGpEndOffset = 56;
9347 static const unsigned SystemZFpOffset = 128;
9348 static const unsigned SystemZFpEndOffset = 160;
9349 static const unsigned SystemZMaxVrArgs = 8;
9350 static const unsigned SystemZRegSaveAreaSize = 160;
9351 static const unsigned SystemZOverflowOffset = 160;
9352 static const unsigned SystemZVAListTagSize = 32;
9353 static const unsigned SystemZOverflowArgAreaPtrOffset = 16;
9354 static const unsigned SystemZRegSaveAreaPtrOffset = 24;
9355
9356 bool IsSoftFloatABI;
9357 AllocaInst *VAArgTLSCopy = nullptr;
9358 AllocaInst *VAArgTLSOriginCopy = nullptr;
9359 Value *VAArgOverflowSize = nullptr;
9360
9361 enum class ArgKind {
9362 GeneralPurpose,
9363 FloatingPoint,
9364 Vector,
9365 Memory,
9366 Indirect,
9367 };
9368
9369 enum class ShadowExtension { None, Zero, Sign };
9370
9371 VarArgSystemZHelper(Function &F, MemorySanitizer &MS,
9372 MemorySanitizerVisitor &MSV)
9373 : VarArgHelperBase(F, MS, MSV, SystemZVAListTagSize),
9374 IsSoftFloatABI(F.getFnAttribute("use-soft-float").getValueAsBool()) {}
9375
9376 ArgKind classifyArgument(Type *T) {
9377 // T is a SystemZABIInfo::classifyArgumentType() output, and there are
9378 // only a few possibilities of what it can be. In particular, enums, single
9379 // element structs and large types have already been taken care of.
9380
9381 // Some i128 and fp128 arguments are converted to pointers only in the
9382 // back end.
9383 if (T->isIntegerTy(128) || T->isFP128Ty())
9384 return ArgKind::Indirect;
9385 if (T->isFloatingPointTy())
9386 return IsSoftFloatABI ? ArgKind::GeneralPurpose : ArgKind::FloatingPoint;
9387 if (T->isIntegerTy() || T->isPointerTy())
9388 return ArgKind::GeneralPurpose;
9389 if (T->isVectorTy())
9390 return ArgKind::Vector;
9391 return ArgKind::Memory;
9392 }
9393
9394 ShadowExtension getShadowExtension(const CallBase &CB, unsigned ArgNo) {
9395 // ABI says: "One of the simple integer types no more than 64 bits wide.
9396 // ... If such an argument is shorter than 64 bits, replace it by a full
9397 // 64-bit integer representing the same number, using sign or zero
9398 // extension". Shadow for an integer argument has the same type as the
9399 // argument itself, so it can be sign or zero extended as well.
9400 bool ZExt = CB.paramHasAttr(ArgNo, Attribute::ZExt);
9401 bool SExt = CB.paramHasAttr(ArgNo, Attribute::SExt);
9402 if (ZExt) {
9403 assert(!SExt);
9404 return ShadowExtension::Zero;
9405 }
9406 if (SExt) {
9407 assert(!ZExt);
9408 return ShadowExtension::Sign;
9409 }
9410 return ShadowExtension::None;
9411 }
9412
9413 void visitCallBase(CallBase &CB, IRBuilder<> &IRB) override {
9414 unsigned GpOffset = SystemZGpOffset;
9415 unsigned FpOffset = SystemZFpOffset;
9416 unsigned VrIndex = 0;
9417 unsigned OverflowOffset = SystemZOverflowOffset;
9418 const DataLayout &DL = F.getDataLayout();
9419 for (const auto &[ArgNo, A] : llvm::enumerate(CB.args())) {
9420 bool IsFixed = ArgNo < CB.getFunctionType()->getNumParams();
9421 // SystemZABIInfo does not produce ByVal parameters.
9422 assert(!CB.isByValArgument(ArgNo));
9423 Type *T = A->getType();
9424 ArgKind AK = classifyArgument(T);
9425 if (AK == ArgKind::Indirect) {
9426 T = MS.PtrTy;
9427 AK = ArgKind::GeneralPurpose;
9428 }
9429 if (AK == ArgKind::GeneralPurpose && GpOffset >= SystemZGpEndOffset)
9430 AK = ArgKind::Memory;
9431 if (AK == ArgKind::FloatingPoint && FpOffset >= SystemZFpEndOffset)
9432 AK = ArgKind::Memory;
9433 if (AK == ArgKind::Vector && (VrIndex >= SystemZMaxVrArgs || !IsFixed))
9434 AK = ArgKind::Memory;
9435 Value *ShadowBase = nullptr;
9436 Value *OriginBase = nullptr;
9437 ShadowExtension SE = ShadowExtension::None;
9438 switch (AK) {
9439 case ArgKind::GeneralPurpose: {
9440 // Always keep track of GpOffset, but store shadow only for varargs.
9441 uint64_t ArgSize = 8;
9442 if (GpOffset + ArgSize <= kParamTLSSize) {
9443 if (!IsFixed) {
9444 SE = getShadowExtension(CB, ArgNo);
9445 uint64_t GapSize = 0;
9446 if (SE == ShadowExtension::None) {
9447 uint64_t ArgAllocSize = DL.getTypeAllocSize(T);
9448 assert(ArgAllocSize <= ArgSize);
9449 GapSize = ArgSize - ArgAllocSize;
9450 }
9451 ShadowBase = getShadowAddrForVAArgument(IRB, GpOffset + GapSize);
9452 if (MS.TrackOrigins)
9453 OriginBase = getOriginPtrForVAArgument(IRB, GpOffset + GapSize);
9454 }
9455 GpOffset += ArgSize;
9456 } else {
9457 GpOffset = kParamTLSSize;
9458 }
9459 break;
9460 }
9461 case ArgKind::FloatingPoint: {
9462 // Always keep track of FpOffset, but store shadow only for varargs.
9463 uint64_t ArgSize = 8;
9464 if (FpOffset + ArgSize <= kParamTLSSize) {
9465 if (!IsFixed) {
9466 // PoP says: "A short floating-point datum requires only the
9467 // left-most 32 bit positions of a floating-point register".
9468 // Therefore, in contrast to AK_GeneralPurpose and AK_Memory,
9469 // don't extend shadow and don't mind the gap.
9470 ShadowBase = getShadowAddrForVAArgument(IRB, FpOffset);
9471 if (MS.TrackOrigins)
9472 OriginBase = getOriginPtrForVAArgument(IRB, FpOffset);
9473 }
9474 FpOffset += ArgSize;
9475 } else {
9476 FpOffset = kParamTLSSize;
9477 }
9478 break;
9479 }
9480 case ArgKind::Vector: {
9481 // Keep track of VrIndex. No need to store shadow, since vector varargs
9482 // go through AK_Memory.
9483 assert(IsFixed);
9484 VrIndex++;
9485 break;
9486 }
9487 case ArgKind::Memory: {
9488 // Keep track of OverflowOffset and store shadow only for varargs.
9489 // Ignore fixed args, since we need to copy only the vararg portion of
9490 // the overflow area shadow.
9491 if (!IsFixed) {
9492 uint64_t ArgAllocSize = DL.getTypeAllocSize(T);
9493 uint64_t ArgSize = alignTo(ArgAllocSize, 8);
9494 if (OverflowOffset + ArgSize <= kParamTLSSize) {
9495 SE = getShadowExtension(CB, ArgNo);
9496 uint64_t GapSize =
9497 SE == ShadowExtension::None ? ArgSize - ArgAllocSize : 0;
9498 ShadowBase =
9499 getShadowAddrForVAArgument(IRB, OverflowOffset + GapSize);
9500 if (MS.TrackOrigins)
9501 OriginBase =
9502 getOriginPtrForVAArgument(IRB, OverflowOffset + GapSize);
9503 OverflowOffset += ArgSize;
9504 } else {
9505 OverflowOffset = kParamTLSSize;
9506 }
9507 }
9508 break;
9509 }
9510 case ArgKind::Indirect:
9511 llvm_unreachable("Indirect must be converted to GeneralPurpose");
9512 }
9513 if (ShadowBase == nullptr)
9514 continue;
9515 Value *Shadow = MSV.getShadow(A);
9516 if (SE != ShadowExtension::None)
9517 Shadow = MSV.CreateShadowCast(IRB, Shadow, IRB.getInt64Ty(),
9518 /*Signed*/ SE == ShadowExtension::Sign);
9519 ShadowBase = IRB.CreateIntToPtr(ShadowBase, MS.PtrTy, "_msarg_va_s");
9520 IRB.CreateStore(Shadow, ShadowBase);
9521 if (MS.TrackOrigins) {
9522 Value *Origin = MSV.getOrigin(A);
9523 TypeSize StoreSize = DL.getTypeStoreSize(Shadow->getType());
9524 MSV.paintOrigin(IRB, Origin, OriginBase, StoreSize,
9526 }
9527 }
9528 Constant *OverflowSize = ConstantInt::get(
9529 IRB.getInt64Ty(), OverflowOffset - SystemZOverflowOffset);
9530 IRB.CreateStore(OverflowSize, MS.VAArgOverflowSizeTLS);
9531 }
9532
9533 void copyRegSaveArea(IRBuilder<> &IRB, Value *VAListTag) {
9534 Value *RegSaveAreaPtrPtr = IRB.CreateIntToPtr(
9535 IRB.CreateAdd(
9536 IRB.CreatePtrToInt(VAListTag, MS.IntptrTy),
9537 ConstantInt::get(MS.IntptrTy, SystemZRegSaveAreaPtrOffset)),
9538 MS.PtrTy);
9539 Value *RegSaveAreaPtr = IRB.CreateLoad(MS.PtrTy, RegSaveAreaPtrPtr);
9540 Value *RegSaveAreaShadowPtr, *RegSaveAreaOriginPtr;
9541 const Align Alignment = Align(8);
9542 std::tie(RegSaveAreaShadowPtr, RegSaveAreaOriginPtr) =
9543 MSV.getShadowOriginPtr(RegSaveAreaPtr, IRB, IRB.getInt8Ty(), Alignment,
9544 /*isStore*/ true);
9545 // TODO(iii): copy only fragments filled by visitCallBase()
9546 // TODO(iii): support packed-stack && !use-soft-float
9547 // For use-soft-float functions, it is enough to copy just the GPRs.
9548 unsigned RegSaveAreaSize =
9549 IsSoftFloatABI ? SystemZGpEndOffset : SystemZRegSaveAreaSize;
9550 IRB.CreateMemCpy(RegSaveAreaShadowPtr, Alignment, VAArgTLSCopy, Alignment,
9551 RegSaveAreaSize);
9552 if (MS.TrackOrigins)
9553 IRB.CreateMemCpy(RegSaveAreaOriginPtr, Alignment, VAArgTLSOriginCopy,
9554 Alignment, RegSaveAreaSize);
9555 }
9556
9557 // FIXME: This implementation limits OverflowOffset to kParamTLSSize, so we
9558 // don't know real overflow size and can't clear shadow beyond kParamTLSSize.
9559 void copyOverflowArea(IRBuilder<> &IRB, Value *VAListTag) {
9560 Value *OverflowArgAreaPtrPtr = IRB.CreateIntToPtr(
9561 IRB.CreateAdd(
9562 IRB.CreatePtrToInt(VAListTag, MS.IntptrTy),
9563 ConstantInt::get(MS.IntptrTy, SystemZOverflowArgAreaPtrOffset)),
9564 MS.PtrTy);
9565 Value *OverflowArgAreaPtr = IRB.CreateLoad(MS.PtrTy, OverflowArgAreaPtrPtr);
9566 Value *OverflowArgAreaShadowPtr, *OverflowArgAreaOriginPtr;
9567 const Align Alignment = Align(8);
9568 std::tie(OverflowArgAreaShadowPtr, OverflowArgAreaOriginPtr) =
9569 MSV.getShadowOriginPtr(OverflowArgAreaPtr, IRB, IRB.getInt8Ty(),
9570 Alignment, /*isStore*/ true);
9571 Value *SrcPtr = IRB.CreateConstGEP1_32(IRB.getInt8Ty(), VAArgTLSCopy,
9572 SystemZOverflowOffset);
9573 IRB.CreateMemCpy(OverflowArgAreaShadowPtr, Alignment, SrcPtr, Alignment,
9574 VAArgOverflowSize);
9575 if (MS.TrackOrigins) {
9576 SrcPtr = IRB.CreateConstGEP1_32(IRB.getInt8Ty(), VAArgTLSOriginCopy,
9577 SystemZOverflowOffset);
9578 IRB.CreateMemCpy(OverflowArgAreaOriginPtr, Alignment, SrcPtr, Alignment,
9579 VAArgOverflowSize);
9580 }
9581 }
9582
9583 void finalizeInstrumentation() override {
9584 assert(!VAArgOverflowSize && !VAArgTLSCopy &&
9585 "finalizeInstrumentation called twice");
9586 if (!VAStartInstrumentationList.empty()) {
9587 // If there is a va_start in this function, make a backup copy of
9588 // va_arg_tls somewhere in the function entry block.
9589 IRBuilder<> IRB(MSV.FnPrologueEnd);
9590 VAArgOverflowSize =
9591 IRB.CreateLoad(IRB.getInt64Ty(), MS.VAArgOverflowSizeTLS);
9592 Value *CopySize =
9593 IRB.CreateAdd(ConstantInt::get(MS.IntptrTy, SystemZOverflowOffset),
9594 VAArgOverflowSize);
9595 VAArgTLSCopy = IRB.CreateAlloca(Type::getInt8Ty(*MS.C), CopySize);
9596 VAArgTLSCopy->setAlignment(kShadowTLSAlignment);
9597 IRB.CreateMemSet(VAArgTLSCopy, Constant::getNullValue(IRB.getInt8Ty()),
9598 CopySize, kShadowTLSAlignment, false);
9599
9600 Value *SrcSize = IRB.CreateBinaryIntrinsic(
9601 Intrinsic::umin, CopySize,
9602 ConstantInt::get(MS.IntptrTy, kParamTLSSize));
9603 IRB.CreateMemCpy(VAArgTLSCopy, kShadowTLSAlignment, MS.VAArgTLS,
9604 kShadowTLSAlignment, SrcSize);
9605 if (MS.TrackOrigins) {
9606 VAArgTLSOriginCopy = IRB.CreateAlloca(Type::getInt8Ty(*MS.C), CopySize);
9607 VAArgTLSOriginCopy->setAlignment(kShadowTLSAlignment);
9608 IRB.CreateMemCpy(VAArgTLSOriginCopy, kShadowTLSAlignment,
9609 MS.VAArgOriginTLS, kShadowTLSAlignment, SrcSize);
9610 }
9611 }
9612
9613 // Instrument va_start.
9614 // Copy va_list shadow from the backup copy of the TLS contents.
9615 for (CallInst *OrigInst : VAStartInstrumentationList) {
9616 NextNodeIRBuilder IRB(OrigInst);
9617 Value *VAListTag = OrigInst->getArgOperand(0);
9618 copyRegSaveArea(IRB, VAListTag);
9619 copyOverflowArea(IRB, VAListTag);
9620 }
9621 }
9622};
9623
9624/// i386-specific implementation of VarArgHelper.
9625struct VarArgI386Helper : public VarArgStackModelHelperBase {
9626 VarArgI386Helper(Function &F, MemorySanitizer &MS,
9627 MemorySanitizerVisitor &MSV)
9628 : VarArgStackModelHelperBase(F, MS, MSV, /*VAListTagSize=*/4) {}
9629
9630 void visitCallBase(CallBase &CB, IRBuilder<> &IRB) override {
9631 const DataLayout &DL = F.getDataLayout();
9632 unsigned IntptrSize = DL.getTypeStoreSize(MS.IntptrTy);
9633 unsigned VAArgOffset = 0;
9634 for (const auto &[ArgNo, A] : llvm::enumerate(CB.args())) {
9635 bool IsFixed = ArgNo < CB.getFunctionType()->getNumParams();
9636 bool IsByVal = CB.isByValArgument(ArgNo);
9637 if (IsByVal) {
9638 assert(A->getType()->isPointerTy());
9639 Type *RealTy = CB.getParamByValType(ArgNo);
9640 uint64_t ArgSize = DL.getTypeAllocSize(RealTy);
9641 Align ArgAlign = CB.getParamAlign(ArgNo).value_or(Align(IntptrSize));
9642 if (ArgAlign < IntptrSize)
9643 ArgAlign = Align(IntptrSize);
9644 VAArgOffset = alignTo(VAArgOffset, ArgAlign);
9645 if (!IsFixed) {
9646 Value *Base = getShadowPtrForVAArgument(IRB, VAArgOffset, ArgSize);
9647 if (Base) {
9648 Value *AShadowPtr, *AOriginPtr;
9649 std::tie(AShadowPtr, AOriginPtr) =
9650 MSV.getShadowOriginPtr(A, IRB, IRB.getInt8Ty(),
9651 kShadowTLSAlignment, /*isStore*/ false);
9652
9653 IRB.CreateMemCpy(Base, kShadowTLSAlignment, AShadowPtr,
9654 kShadowTLSAlignment, ArgSize);
9655 }
9656 VAArgOffset += alignTo(ArgSize, Align(IntptrSize));
9657 }
9658 } else {
9659 Value *Base;
9660 uint64_t ArgSize = DL.getTypeAllocSize(A->getType());
9661 Align ArgAlign = Align(IntptrSize);
9662 VAArgOffset = alignTo(VAArgOffset, ArgAlign);
9663 if (DL.isBigEndian()) {
9664 // Adjusting the shadow for argument with size < IntptrSize to match
9665 // the placement of bits in big endian system
9666 if (ArgSize < IntptrSize)
9667 VAArgOffset += (IntptrSize - ArgSize);
9668 }
9669 if (!IsFixed) {
9670 Base = getShadowPtrForVAArgument(IRB, VAArgOffset, ArgSize);
9671 if (Base)
9672 IRB.CreateAlignedStore(MSV.getShadow(A), Base, kShadowTLSAlignment);
9673 VAArgOffset += ArgSize;
9674 VAArgOffset = alignTo(VAArgOffset, Align(IntptrSize));
9675 }
9676 }
9677 }
9678
9679 Constant *TotalVAArgSize = ConstantInt::get(MS.IntptrTy, VAArgOffset);
9680 // Here using VAArgOverflowSizeTLS as VAArgSizeTLS to avoid creation of
9681 // a new class member i.e. it is the total size of all VarArgs.
9682 IRB.CreateStore(TotalVAArgSize, MS.VAArgOverflowSizeTLS);
9683 }
9684};
9685
9686/// Implementation of VarArgHelper that is used for ARM32, MIPS, RISCV,
9687/// LoongArch64.
9688struct VarArgGenericHelper : public VarArgStackModelHelperBase {
9689 VarArgGenericHelper(Function &F, MemorySanitizer &MS,
9690 MemorySanitizerVisitor &MSV, const unsigned VAListTagSize)
9691 : VarArgStackModelHelperBase(F, MS, MSV, VAListTagSize) {}
9692
9693 void visitCallBase(CallBase &CB, IRBuilder<> &IRB) override {
9694 unsigned VAArgOffset = 0;
9695 const DataLayout &DL = F.getDataLayout();
9696 unsigned IntptrSize = DL.getTypeStoreSize(MS.IntptrTy);
9697 for (const auto &[ArgNo, A] : llvm::enumerate(CB.args())) {
9698 bool IsFixed = ArgNo < CB.getFunctionType()->getNumParams();
9699 if (IsFixed)
9700 continue;
9701 uint64_t ArgSize = DL.getTypeAllocSize(A->getType());
9702 if (DL.isBigEndian()) {
9703 // Adjusting the shadow for argument with size < IntptrSize to match the
9704 // placement of bits in big endian system
9705 if (ArgSize < IntptrSize)
9706 VAArgOffset += (IntptrSize - ArgSize);
9707 }
9708 Value *Base = getShadowPtrForVAArgument(IRB, VAArgOffset, ArgSize);
9709 VAArgOffset += ArgSize;
9710 VAArgOffset = alignTo(VAArgOffset, IntptrSize);
9711 if (!Base)
9712 continue;
9713 IRB.CreateAlignedStore(MSV.getShadow(A), Base, kShadowTLSAlignment);
9714 }
9715
9716 Constant *TotalVAArgSize = ConstantInt::get(MS.IntptrTy, VAArgOffset);
9717 // Here using VAArgOverflowSizeTLS as VAArgSizeTLS to avoid creation of
9718 // a new class member i.e. it is the total size of all VarArgs.
9719 IRB.CreateStore(TotalVAArgSize, MS.VAArgOverflowSizeTLS);
9720 }
9721};
9722
9723// ARM32, Loongarch64, MIPS and RISCV share the same calling conventions
9724// regarding VAArgs.
9725using VarArgARM32Helper = VarArgGenericHelper;
9726using VarArgRISCVHelper = VarArgGenericHelper;
9727using VarArgMIPSHelper = VarArgGenericHelper;
9728using VarArgLoongArch64Helper = VarArgGenericHelper;
9729using VarArgHexagonHelper = VarArgGenericHelper;
9730
9731/// A no-op implementation of VarArgHelper.
9732struct VarArgNoOpHelper : public VarArgHelper {
9733 VarArgNoOpHelper(Function &F, MemorySanitizer &MS,
9734 MemorySanitizerVisitor &MSV) {}
9735
9736 void visitCallBase(CallBase &CB, IRBuilder<> &IRB) override {}
9737
9738 void visitVAStartInst(VAStartInst &I) override {}
9739
9740 void visitVACopyInst(VACopyInst &I) override {}
9741
9742 void finalizeInstrumentation() override {}
9743};
9744
9745} // end anonymous namespace
9746
9747static VarArgHelper *CreateVarArgHelper(Function &Func, MemorySanitizer &Msan,
9748 MemorySanitizerVisitor &Visitor) {
9749 // VarArg handling is only implemented on AMD64. False positives are possible
9750 // on other platforms.
9751 Triple TargetTriple(Func.getParent()->getTargetTriple());
9752
9753 if (TargetTriple.getArch() == Triple::x86)
9754 return new VarArgI386Helper(Func, Msan, Visitor);
9755
9756 if (TargetTriple.getArch() == Triple::x86_64)
9757 return new VarArgAMD64Helper(Func, Msan, Visitor);
9758
9759 if (TargetTriple.isARM())
9760 return new VarArgARM32Helper(Func, Msan, Visitor, /*VAListTagSize=*/4);
9761
9762 if (TargetTriple.isAArch64())
9763 return new VarArgAArch64Helper(Func, Msan, Visitor);
9764
9765 if (TargetTriple.isSystemZ())
9766 return new VarArgSystemZHelper(Func, Msan, Visitor);
9767
9768 // On PowerPC32 VAListTag is a struct
9769 // {char, char, i16 padding, char *, char *}
9770 if (TargetTriple.isPPC32())
9771 return new VarArgPowerPC32Helper(Func, Msan, Visitor);
9772
9773 if (TargetTriple.isPPC64())
9774 return new VarArgPowerPC64Helper(Func, Msan, Visitor);
9775
9776 if (TargetTriple.isRISCV32())
9777 return new VarArgRISCVHelper(Func, Msan, Visitor, /*VAListTagSize=*/4);
9778
9779 if (TargetTriple.isRISCV64())
9780 return new VarArgRISCVHelper(Func, Msan, Visitor, /*VAListTagSize=*/8);
9781
9782 if (TargetTriple.isMIPS32())
9783 return new VarArgMIPSHelper(Func, Msan, Visitor, /*VAListTagSize=*/4);
9784
9785 if (TargetTriple.isMIPS64())
9786 return new VarArgMIPSHelper(Func, Msan, Visitor, /*VAListTagSize=*/8);
9787
9788 if (TargetTriple.isLoongArch64())
9789 return new VarArgLoongArch64Helper(Func, Msan, Visitor,
9790 /*VAListTagSize=*/8);
9791
9792 if (TargetTriple.getArch() == Triple::hexagon)
9793 return new VarArgHexagonHelper(Func, Msan, Visitor, /*VAListTagSize=*/12);
9794
9795 return new VarArgNoOpHelper(Func, Msan, Visitor);
9796}
9797
9798bool MemorySanitizer::sanitizeFunction(Function &F, TargetLibraryInfo &TLI) {
9799 if (!CompileKernel && F.getName() == kMsanModuleCtorName)
9800 return false;
9801
9802 if (F.hasFnAttribute(Attribute::DisableSanitizerInstrumentation))
9803 return false;
9804
9805 MemorySanitizerVisitor Visitor(F, *this, TLI);
9806
9807 // Clear out memory attributes.
9809 B.addAttribute(Attribute::Memory).addAttribute(Attribute::Speculatable);
9810 F.removeFnAttrs(B);
9811
9812 return Visitor.runOnFunction();
9813}
#define Success
const TargetLowering & TLI
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
const AArch64InstrInfo MachineBasicBlock::iterator InsertPt
uint64_t uint64_t
uint64_t Imm
constexpr LLT S1
AMDGPU Uniform Intrinsic Combine
This file implements a class to represent arbitrary precision integral constant values and operations...
static bool isStore(int Opcode)
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
static const size_t kNumberOfAccessSizes
VarLocInsertPt getNextNode(const DbgRecord *DVR)
Atomic ordering constants.
This file contains the simple types necessary to represent the attributes associated with functions a...
#define X(NUM, ENUM, NAME)
Definition ELF.h:665
static GCRegistry::Add< ShadowStackGC > C("shadow-stack", "Very portable GC for uncooperative code generators")
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
static GCRegistry::Add< StatepointGC > D("statepoint-example", "an example strategy for statepoint")
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
This file contains the declarations for the subclasses of Constant, which represent the different fla...
static bool insertModuleCtor(Module &M)
Definition CopyProf.cpp:77
const MemoryMapParams Linux_LoongArch64_MemoryMapParams
const MemoryMapParams Linux_X86_64_MemoryMapParams
static AtomicOrdering addReleaseOrdering(AtomicOrdering AO)
const MemoryMapParams Linux_S390X_MemoryMapParams
static AtomicOrdering addAcquireOrdering(AtomicOrdering AO)
const MemoryMapParams Linux_AArch64_MemoryMapParams
static bool isAMustTailRetVal(Value *RetVal)
This file provides an implementation of debug counters.
#define DEBUG_COUNTER(VARNAME, COUNTERNAME, DESC)
This file defines the DenseMap class.
This file builds on the ADT/GraphTraits.h file to build generic depth first graph iterator.
static bool runOnFunction(Function &F, bool PostInlining)
This is the interface for a simple mod/ref and alias analysis over globals.
static size_t TypeSizeToSizeIndex(uint32_t TypeSize)
#define op(i)
Hexagon Common GEP
#define _
Module.h This file contains the declarations for the Module class.
static LVOptions Options
Definition LVOptions.cpp:25
static bool isZero(Value *V, const DataLayout &DL, DominatorTree *DT, AssumptionCache *AC)
Definition Lint.cpp:550
SmallVector< MachineOperand, 4 > Cond
if(!TBB||Cond.size()< 1) return false
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
static const PlatformMemoryMapParams Linux_S390_MemoryMapParams
static const Align kMinOriginAlignment
static const PlatformMemoryMapParams Linux_X86_MemoryMapParams
static const PlatformMemoryMapParams Linux_LoongArch_MemoryMapParams
static const MemoryMapParams NetBSD_X86_64_MemoryMapParams
static MemorySanitizerOptions resolveOptions(const InstrumentationOptions &Opts, MemorySanitizerOptions O)
static const PlatformMemoryMapParams Linux_MIPS_MemoryMapParams
static const unsigned kOriginSize
static const Align kShadowTLSAlignment
static const PlatformMemoryMapParams Linux_ARM_MemoryMapParams
static Constant * getOrInsertGlobal(Module &M, StringRef Name, Type *Ty)
static const PlatformMemoryMapParams Linux_Hexagon_MemoryMapParams_P
static const MemoryMapParams Linux_I386_MemoryMapParams
const char kMsanInitName[]
OddOrEvenLanes
@ kOddLanes
@ kEvenLanes
@ kBothLanes
static const MemoryMapParams FreeBSD_X86_64_MemoryMapParams
static GlobalVariable * createPrivateConstGlobalForString(Module &M, StringRef Str)
Create a non-const global initialized with the given string.
static const PlatformMemoryMapParams Linux_PowerPC_MemoryMapParams
static const size_t kNumberOfAccessSizes
static VarArgHelper * CreateVarArgHelper(Function &Func, MemorySanitizer &Msan, MemorySanitizerVisitor &Visitor)
static const MemoryMapParams Linux_MIPS64_MemoryMapParams
static const MemoryMapParams Linux_PowerPC64_MemoryMapParams
static const MemoryMapParams Linux_Hexagon_MemoryMapParams
static const PlatformMemoryMapParams FreeBSD_X86_MemoryMapParams
static const PlatformMemoryMapParams FreeBSD_ARM_MemoryMapParams
static const unsigned kParamTLSSize
static const PlatformMemoryMapParams NetBSD_X86_MemoryMapParams
static const unsigned kRetvalTLSSize
static const MemoryMapParams FreeBSD_AArch64_MemoryMapParams
const char kMsanModuleCtorName[]
static const MemoryMapParams FreeBSD_I386_MemoryMapParams
#define T
uint64_t IntrinsicInst * II
FunctionAnalysisManager FAM
static void visit(BasicBlock &Start, std::function< bool(BasicBlock *)> op)
static const char * name
This file implements a set that has insertion order iteration characteristics.
This file defines the SmallPtrSet class.
This file defines the SmallVector class.
This file contains some functions that are useful when dealing with strings.
#define LLVM_DEBUG(...)
Definition Debug.h:119
static SymbolRef::Type getType(const Symbol *Sym)
Definition TapiFile.cpp:39
Value * RHS
Value * LHS
unsigned countr_zero() const
Count the number of trailing zero bits.
Definition APInt.h:1659
static APInt getSignedMinValue(unsigned numBits)
Gets minimum signed value of APInt for a specific bit width.
Definition APInt.h:215
void setAlignment(Align Align)
PassT::Result & getResult(IRUnitT &IR, ExtraArgTs... ExtraArgs)
Get the result of an analysis pass for a given IR unit.
const T & front() const
Get the first element.
Definition ArrayRef.h:144
size_t size() const
Get the array size.
Definition ArrayRef.h:141
static LLVM_ABI ArrayType * get(Type *ElementType, uint64_t NumElements)
This static method is the primary way to construct an ArrayType.
This class stores enough information to efficiently remove some attributes from an existing AttrBuild...
AttributeMask & addAttribute(Attribute::AttrKind Val)
Add an attribute to the mask.
iterator end()
Definition BasicBlock.h:452
LLVM_ABI const_iterator getFirstInsertionPt() const
Returns an iterator to the first instruction in this block that is suitable for inserting a non-PHI i...
LLVM_ABI const BasicBlock * getSinglePredecessor() const
Return the predecessor of this block if it has a single predecessor block.
InstListType::iterator iterator
Instruction iterators...
Definition BasicBlock.h:169
bool isInlineAsm() const
Check if this call is an inline asm statement.
Function * getCalledFunction() const
Returns the function called, or null if this is an indirect function invocation or the function signa...
bool hasRetAttr(Attribute::AttrKind Kind) const
Determine whether the return value has the given attribute.
LLVM_ABI bool paramHasAttr(unsigned ArgNo, Attribute::AttrKind Kind) const
Determine whether the argument or parameter has the given attribute.
bool isByValArgument(unsigned ArgNo) const
Determine whether this argument is passed by value.
void removeFnAttrs(const AttributeMask &AttrsToRemove)
Removes the attributes from the function.
void setCannotMerge()
MaybeAlign getParamAlign(unsigned ArgNo) const
Extract the alignment for a call or parameter (0=unknown).
Type * getParamByValType(unsigned ArgNo) const
Extract the byval type for a call or parameter.
Value * getCalledOperand() const
Type * getParamElementType(unsigned ArgNo) const
Extract the elementtype type for a parameter.
Value * getArgOperand(unsigned i) const
void setArgOperand(unsigned i, Value *v)
FunctionType * getFunctionType() const
iterator_range< User::op_iterator > args()
Iteration adapter for range-for loops.
void addParamAttr(unsigned ArgNo, Attribute::AttrKind Kind)
Adds the attribute to the indicated argument.
Predicate
This enumeration lists the possible predicates for CmpInst subclasses.
Definition InstrTypes.h:740
@ ICMP_SLT
signed less than
Definition InstrTypes.h:769
@ ICMP_SLE
signed less or equal
Definition InstrTypes.h:770
@ ICMP_SGT
signed greater than
Definition InstrTypes.h:767
@ ICMP_SGE
signed greater or equal
Definition InstrTypes.h:768
static LLVM_ABI Constant * get(ArrayType *T, ArrayRef< Constant * > V)
static LLVM_ABI Constant * getString(LLVMContext &Context, StringRef Initializer, bool AddNull=true, bool ByteString=false)
This method constructs a CDS and initializes it with a text string.
static LLVM_ABI Constant * get(LLVMContext &Context, ArrayRef< uint8_t > Elts)
get() constructors - Return a constant with vector type with an element count and element type matchi...
static ConstantInt * getSigned(IntegerType *Ty, int64_t V, bool ImplicitTrunc=false)
Return a ConstantInt with the specified value for the specified type.
Definition Constants.h:135
static LLVM_ABI ConstantInt * getBool(LLVMContext &Context, bool V)
static LLVM_ABI Constant * get(StructType *T, ArrayRef< Constant * > V)
static LLVM_ABI Constant * getSplat(ElementCount EC, Constant *Elt)
Return a ConstantVector with the specified constant in each element.
static LLVM_ABI Constant * get(ArrayRef< Constant * > V)
This is an important base class in LLVM.
Definition Constant.h:44
bool isNullValue() const
Return true if this is the value that would be returned by getNullValue.
Definition Constant.h:65
static LLVM_ABI Constant * getAllOnesValue(Type *Ty)
LLVM_ABI bool isAllOnesValue() const
Return true if this is the value that would be returned by getAllOnesValue.
Definition Constants.cpp:62
static LLVM_ABI Constant * getNullValue(Type *Ty)
Constructor to create a '0' constant of arbitrary type.
LLVM_ABI Constant * getAggregateElement(unsigned Elt) const
For aggregates (struct/array/vector) return the constant that corresponds to the specified element if...
static bool shouldExecute(CounterInfo &Counter)
bool empty() const
Definition DenseMap.h:716
unsigned getNumElements() const
static LLVM_ABI FixedVectorType * get(Type *ElementType, unsigned NumElts)
Definition Type.cpp:838
static FixedVectorType * getHalfElementsVectorType(FixedVectorType *VTy)
A handy container for a FunctionType+Callee-pointer pair, which can be passed around as a single enti...
unsigned getNumParams() const
Return the number of fixed parameters this function type requires.
static GEPNoWrapFlags inBounds()
LLVM_ABI void setComdat(Comdat *C)
Definition Globals.cpp:287
@ PrivateLinkage
Like Internal, but omit from symbol table.
Definition GlobalValue.h:61
@ ExternalLinkage
Externally visible function.
Definition GlobalValue.h:53
Analysis pass providing a never-invalidated alias analysis result.
ConstantInt * getInt1(bool V)
Get a constant value representing either true or false.
Definition IRBuilder.h:446
LLVM_ABI CallInst * CreateIntrinsicWithoutFolding(Intrinsic::ID ID, ArrayRef< Type * > OverloadTypes, ArrayRef< Value * > Args, FMFSource FMFSource={}, const Twine &Name="", ArrayRef< OperandBundleDef > OpBundles={})
Create a call to intrinsic ID with Args, mangled using OverloadTypes.
LLVM_ABI Value * CreateAndReduce(Value *Src)
Create a vector int AND reduction intrinsic of the source vector.
Value * CreateInsertElement(Type *VecTy, Value *NewElt, Value *Idx, const Twine &Name="")
Definition IRBuilder.h:2748
Value * CreatePtrAddWithUnsignedOffset(Value *Ptr, uint64_t Offset, const Twine &Name="", GEPNoWrapFlags NW=GEPNoWrapFlags::none())
Create a ptradd with an unsigned constant offset.
Definition IRBuilder.h:2113
Value * CreateConstGEP1_32(Type *Ty, Value *Ptr, unsigned Idx0, const Twine &Name="")
Definition IRBuilder.h:2026
AllocaInst * CreateAlloca(Type *Ty, unsigned AddrSpace, Value *ArraySize=nullptr, const Twine &Name="")
Definition IRBuilder.h:1886
IntegerType * getInt1Ty()
Fetch the type representing a single bit.
Definition IRBuilder.h:513
LLVM_ABI CallInst * CreateMaskedCompressStore(Value *Val, Value *Ptr, MaybeAlign Align, Value *Mask=nullptr)
Create a call to Masked Compress Store intrinsic.
Value * CreateInsertValue(Value *Agg, Value *Val, ArrayRef< unsigned > Idxs, const Twine &Name="")
Definition IRBuilder.h:2802
LLVM_ABI Value * CreateAllocationSize(Type *DestTy, AllocaInst *AI)
Get allocation size of an alloca as a runtime Value* (handles both static and dynamic allocas and vsc...
Value * CreateExtractElement(Value *Vec, Value *Idx, const Twine &Name="")
Definition IRBuilder.h:2736
IntegerType * getIntNTy(unsigned N)
Fetch the type representing an N-bit integer.
Definition IRBuilder.h:541
LoadInst * CreateAlignedLoad(Type *Ty, Value *Ptr, MaybeAlign Align, const char *Name)
Definition IRBuilder.h:1940
Value * CreateZExtOrTrunc(Value *V, Type *DestTy, const Twine &Name="")
Create a ZExt or Trunc from the integer value V to DestTy.
Definition IRBuilder.h:2215
CallInst * CreateMemCpy(Value *Dst, MaybeAlign DstAlign, Value *Src, MaybeAlign SrcAlign, uint64_t Size, bool isVolatile=false, const AAMDNodes &AAInfo=AAMDNodes())
Create and insert a memcpy between the specified pointers.
Definition IRBuilder.h:657
Value * CreatePointerCast(Value *V, Type *DestTy, const Twine &Name="")
Definition IRBuilder.h:2373
Value * CreateExtractValue(Value *Agg, ArrayRef< unsigned > Idxs, const Twine &Name="")
Definition IRBuilder.h:2795
LLVM_ABI CallInst * CreateMaskedLoad(Type *Ty, Value *Ptr, Align Alignment, Value *Mask, Value *PassThru=nullptr, const Twine &Name="")
Create a call to Masked Load intrinsic.
LLVM_ABI Value * CreateSelect(Value *C, Value *True, Value *False, const Twine &Name="", Instruction *MDFrom=nullptr)
BasicBlock::iterator GetInsertPoint() const
Definition IRBuilder.h:177
Value * CreateSExt(Value *V, Type *DestTy, const Twine &Name="")
Definition IRBuilder.h:2209
Value * CreateIntToPtr(Value *V, Type *DestTy, const Twine &Name="")
Definition IRBuilder.h:2314
Value * CreateLShr(Value *LHS, Value *RHS, const Twine &Name="", bool isExact=false)
Definition IRBuilder.h:1534
IntegerType * getInt32Ty()
Fetch the type representing a 32-bit integer.
Definition IRBuilder.h:528
ConstantInt * getInt8(uint8_t C)
Get a constant 8-bit value.
Definition IRBuilder.h:461
IntegerType * getInt64Ty()
Fetch the type representing a 64-bit integer.
Definition IRBuilder.h:533
Value * CreateICmp(CmpInst::Predicate P, Value *LHS, Value *RHS, const Twine &Name="", bool HasSameSign=false)
Definition IRBuilder.h:2568
LLVM_ABI Value * CreateGEP(Type *Ty, Value *Ptr, ArrayRef< Value * > IdxList, const Twine &Name="", GEPNoWrapFlags NW=GEPNoWrapFlags::none())
Value * CreateUDiv(Value *LHS, Value *RHS, const Twine &Name="", bool isExact=false)
Definition IRBuilder.h:1475
Value * CreateICmpNE(Value *LHS, Value *RHS, const Twine &Name="")
Definition IRBuilder.h:2462
IntegerType * getInt16Ty()
Fetch the type representing a 16-bit integer.
Definition IRBuilder.h:523
Value * CreateNeg(Value *V, const Twine &Name="", bool HasNSW=false)
Definition IRBuilder.h:1832
LLVM_ABI Value * CreateBinaryIntrinsic(Intrinsic::ID ID, Value *LHS, Value *RHS, FMFSource FMFSource={}, const Twine &Name="")
Create a call to intrinsic ID with 2 operands which is mangled on the first type.
LLVM_ABI Value * CreateOrReduce(Value *Src)
Create a vector int OR reduction intrinsic of the source vector.
ConstantInt * getInt32(uint32_t C)
Get a constant 32-bit value.
Definition IRBuilder.h:471
PHINode * CreatePHI(Type *Ty, unsigned NumReservedValues, const Twine &Name="")
Definition IRBuilder.h:2626
Value * CreateNot(Value *V, const Twine &Name="")
Definition IRBuilder.h:1856
Value * CreateICmpEQ(Value *LHS, Value *RHS, const Twine &Name="")
Definition IRBuilder.h:2458
LLVM_ABI DebugLoc getCurrentDebugLocation() const
Get location information used by debugging information.
Definition IRBuilder.cpp:67
Value * CreateSub(Value *LHS, Value *RHS, const Twine &Name="", bool HasNUW=false, bool HasNSW=false)
Definition IRBuilder.h:1441
Value * CreateBitCast(Value *V, Type *DestTy, const Twine &Name="")
Definition IRBuilder.h:2319
ConstantInt * getIntN(unsigned N, uint64_t C)
Get a constant N-bit value, zero extended from a 64-bit value.
Definition IRBuilder.h:481
LoadInst * CreateLoad(Type *Ty, Value *Ptr, const char *Name)
Provided to resolve 'CreateLoad(Ty, Ptr, "...")' correctly, instead of converting the string to 'bool...
Definition IRBuilder.h:1913
Value * CreateShl(Value *LHS, Value *RHS, const Twine &Name="", bool HasNUW=false, bool HasNSW=false)
Definition IRBuilder.h:1513
CallInst * CreateMemSet(Value *Ptr, Value *Val, uint64_t Size, MaybeAlign Align, bool isVolatile=false, const AAMDNodes &AAInfo=AAMDNodes())
Create and insert a memset to the specified pointer and the specified value.
Definition IRBuilder.h:602
Value * CreateZExt(Value *V, Type *DestTy, const Twine &Name="", bool IsNonNeg=false)
Definition IRBuilder.h:2197
Value * CreateShuffleVector(Value *V1, Value *V2, Value *Mask, const Twine &Name="")
Definition IRBuilder.h:2770
LLVMContext & getContext() const
Definition IRBuilder.h:178
Value * CreateAnd(Value *LHS, Value *RHS, const Twine &Name="")
Definition IRBuilder.h:1572
LLVM_ABI Value * CreateIntrinsic(Intrinsic::ID ID, ArrayRef< Type * > OverloadTypes, ArrayRef< Value * > Args, FMFSource FMFSource={}, const Twine &Name="", ArrayRef< OperandBundleDef > OpBundles={}, function_ref< void(CallInst *)> SetFn=[](CallInst *) {})
Variant to create a possibly constant-folded intrinsic.
StoreInst * CreateStore(Value *Val, Value *Ptr, bool isVolatile=false)
Definition IRBuilder.h:1931
LLVM_ABI CallInst * CreateMaskedStore(Value *Val, Value *Ptr, Align Alignment, Value *Mask)
Create a call to Masked Store intrinsic.
Value * CreateAdd(Value *LHS, Value *RHS, const Twine &Name="", bool HasNUW=false, bool HasNSW=false)
Definition IRBuilder.h:1424
Value * CreatePtrToInt(Value *V, Type *DestTy, const Twine &Name="")
Definition IRBuilder.h:2309
Value * CreateIsNotNull(Value *Arg, const Twine &Name="")
Return a boolean value testing if Arg != 0.
Definition IRBuilder.h:2842
CallInst * CreateCall(FunctionType *FTy, Value *Callee, ArrayRef< Value * > Args={}, const Twine &Name="", MDNode *FPMathTag=nullptr)
Definition IRBuilder.h:2640
Value * CreateTrunc(Value *V, Type *DestTy, const Twine &Name="", bool IsNUW=false, bool IsNSW=false)
Definition IRBuilder.h:2183
PointerType * getPtrTy(unsigned AddrSpace=0)
Fetch the type representing a pointer.
Definition IRBuilder.h:571
Value * CreateBinOp(Instruction::BinaryOps Opc, Value *LHS, Value *RHS, const Twine &Name="", MDNode *FPMathTag=nullptr)
Definition IRBuilder.h:1733
Value * CreateICmpSLT(Value *LHS, Value *RHS, const Twine &Name="")
Definition IRBuilder.h:2490
LLVM_ABI Value * CreateTypeSize(Type *Ty, TypeSize Size)
Create an expression which evaluates to the number of units in Size at runtime.
Value * CreateICmpUGE(Value *LHS, Value *RHS, const Twine &Name="")
Definition IRBuilder.h:2470
Value * CreateIntCast(Value *V, Type *DestTy, bool isSigned, const Twine &Name="")
Definition IRBuilder.h:2399
Value * CreateIsNull(Value *Arg, const Twine &Name="")
Return a boolean value testing if Arg == 0.
Definition IRBuilder.h:2837
void SetInsertPoint(BasicBlock *TheBB)
This specifies that created instructions should be appended to the end of the specified block.
Definition IRBuilder.h:197
Type * getVoidTy()
Fetch the type representing void.
Definition IRBuilder.h:566
StoreInst * CreateAlignedStore(Value *Val, Value *Ptr, MaybeAlign Align, bool isVolatile=false)
Definition IRBuilder.h:1959
LLVM_ABI CallInst * CreateMaskedExpandLoad(Type *Ty, Value *Ptr, MaybeAlign Align, Value *Mask=nullptr, Value *PassThru=nullptr, const Twine &Name="")
Create a call to Masked Expand Load intrinsic.
Value * CreateInBoundsPtrAdd(Value *Ptr, Value *Offset, const Twine &Name="")
Definition IRBuilder.h:2105
Value * CreateAShr(Value *LHS, Value *RHS, const Twine &Name="", bool isExact=false)
Definition IRBuilder.h:1553
Value * CreateXor(Value *LHS, Value *RHS, const Twine &Name="")
Definition IRBuilder.h:1624
Value * CreateOr(Value *LHS, Value *RHS, const Twine &Name="", bool IsDisjoint=false)
Definition IRBuilder.h:1594
IntegerType * getInt8Ty()
Fetch the type representing an 8-bit integer.
Definition IRBuilder.h:518
Value * CreateMul(Value *LHS, Value *RHS, const Twine &Name="", bool HasNUW=false, bool HasNSW=false)
Definition IRBuilder.h:1458
LLVM_ABI CallInst * CreateMaskedScatter(Value *Val, Value *Ptrs, Align Alignment, Value *Mask=nullptr)
Create a call to Masked Scatter intrinsic.
LLVM_ABI CallInst * CreateMaskedGather(Type *Ty, Value *Ptrs, Align Alignment, Value *Mask=nullptr, Value *PassThru=nullptr, const Twine &Name="")
Create a call to Masked Gather intrinsic.
Value * CreateFCmpULT(Value *LHS, Value *RHS, const Twine &Name="", MDNode *FPMathTag=nullptr)
Definition IRBuilder.h:2553
This provides a uniform API for creating instructions and inserting them into a basic block: either a...
Definition IRBuilder.h:2990
std::vector< ConstraintInfo > ConstraintInfoVector
Definition InlineAsm.h:124
void visit(Iterator Start, Iterator End)
Definition InstVisitor.h:87
const DebugLoc & getDebugLoc() const
Return the debug location for this node as a DebugLoc.
LLVM_ABI InstListType::iterator eraseFromParent()
This method unlinks 'this' from the containing basic block and deletes it.
MDNode * getMetadata(unsigned KindID) const
Get the metadata of given kind attached to this Instruction.
LLVM_ABI bool comesBefore(const Instruction *Other) const
Given an instruction Other in the same basic block as this instruction, return true if this instructi...
static LLVM_ABI IntegerType * get(LLVMContext &C, unsigned NumBits)
This static method is the primary way of constructing an IntegerType.
Definition Type.cpp:333
LLVM_ABI MDNode * createUnlikelyBranchWeights()
Return metadata containing two branch weights, with significant bias towards false destination.
Definition MDBuilder.cpp:48
A Module instance is used to store all the information related to an LLVM module.
Definition Module.h:68
void addIncoming(Value *V, BasicBlock *BB)
Add an incoming value to the end of the PHI list.
static LLVM_ABI PoisonValue * get(Type *T)
Static factory methods - Return an 'poison' object of the specified type.
A set of analyses that are preserved following a run of a transformation pass.
Definition Analysis.h:112
static PreservedAnalyses none()
Convenience factory function for the empty preserved set.
Definition Analysis.h:115
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
Definition Analysis.h:118
PreservedAnalyses & abandon()
Mark an analysis as abandoned.
Definition Analysis.h:171
bool remove(const value_type &X)
Remove an item from the set vector.
Definition SetVector.h:187
bool insert(const value_type &X)
Insert a new element into the SetVector.
Definition SetVector.h:157
void append(ItTy in_start, ItTy in_end)
Add the specified range to the end of the SmallVector.
void push_back(const T &Elt)
Represent a constant reference to a string, i.e.
Definition StringRef.h:56
static LLVM_ABI StructType * get(LLVMContext &Context, ArrayRef< Type * > Elements, bool isPacked=false)
This static method is the primary way to create a literal StructType.
Definition Type.cpp:462
unsigned getNumElements() const
Random access to the elements.
Type * getElementType(unsigned N) const
Analysis pass providing the TargetLibraryInfo.
Provides information about what library functions are available for the current target.
Triple - Helper class for working with autoconf configuration names.
Definition Triple.h:48
bool isMIPS64() const
Tests whether the target is MIPS 64-bit (little and big endian).
Definition Triple.h:1139
@ loongarch64
Definition Triple.h:66
bool isRISCV32() const
Tests whether the target is 32-bit RISC-V.
Definition Triple.h:1180
bool isPPC32() const
Tests whether the target is 32-bit PowerPC (little and big endian).
Definition Triple.h:1156
ArchType getArch() const
Get the parsed architecture type of this triple.
Definition Triple.h:518
bool isRISCV64() const
Tests whether the target is 64-bit RISC-V.
Definition Triple.h:1185
bool isLoongArch64() const
Tests whether the target is 64-bit LoongArch.
Definition Triple.h:1128
bool isMIPS32() const
Tests whether the target is MIPS 32-bit (little and big endian).
Definition Triple.h:1134
bool isARM() const
Tests whether the target is ARM (little and big endian).
Definition Triple.h:1012
bool isPPC64() const
Tests whether the target is 64-bit PowerPC (little and big endian).
Definition Triple.h:1161
bool isAArch64() const
Tests whether the target is AArch64 (little and big endian).
Definition Triple.h:1105
bool isSystemZ() const
Tests whether the target is SystemZ.
Definition Triple.h:1204
The instances of the Type class are immutable: once they are created, they are never changed.
Definition Type.h:46
LLVM_ABI unsigned getIntegerBitWidth() const
bool isVectorTy() const
True if this is an instance of VectorType.
Definition Type.h:283
bool isArrayTy() const
True if this is an instance of ArrayType.
Definition Type.h:274
bool isIntOrIntVectorTy() const
Return true if this is an integer type or a vector of integer types.
Definition Type.h:258
bool isPointerTy() const
True if this is an instance of PointerType.
Definition Type.h:277
Type * getArrayElementType() const
Definition Type.h:427
LLVM_ABI unsigned getPointerAddressSpace() const
Get the address space of this pointer or pointer vector type.
bool isPPC_FP128Ty() const
Return true if this is powerpc long double.
Definition Type.h:167
bool isSized() const
Return true if it makes sense to take the size of this type.
Definition Type.h:321
static LLVM_ABI Type * getVoidTy(LLVMContext &C)
Definition Type.cpp:267
unsigned getScalarSizeInBits() const LLVM_READONLY
If this is a vector type, return the getPrimitiveSizeInBits value for the element type.
Definition Type.h:354
Type * getScalarType() const
If this is a vector type, return the element type, otherwise return 'this'.
Definition Type.h:370
LLVM_ABI TypeSize getPrimitiveSizeInBits() const LLVM_READONLY
Return the basic size of this type if it is a primitive type.
Definition Type.cpp:187
bool isFloatingPointTy() const
Return true if this is one of the floating-point types.
Definition Type.h:186
LLVM_ABI bool isScalableTy() const
Return true if this is a type whose size is a known multiple of vscale.
Definition Type.cpp:61
bool isIntOrPtrTy() const
Return true if this is an integer type or a pointer type.
Definition Type.h:265
bool isIntegerTy() const
True if this is an instance of IntegerType.
Definition Type.h:252
bool isFPOrFPVectorTy() const
Return true if this is a FP type or a vector of FP.
Definition Type.h:222
bool isVoidTy() const
Return true if this is 'void'.
Definition Type.h:141
Value * getOperand(unsigned i) const
Definition User.h:207
unsigned getNumOperands() const
Definition User.h:229
size_type count(const KeyT &Val) const
Return 1 if the specified key is in the map, 0 otherwise.
Definition ValueMap.h:156
Type * getType() const
All values are typed, get the type of this value.
Definition Value.h:257
LLVM_ABI void setName(const Twine &Name)
Change the name of the value.
Definition Value.cpp:389
LLVM_ABI StringRef getName() const
Return a constant reference to the value's name.
Definition Value.cpp:314
ElementCount getElementCount() const
Return an ElementCount instance to represent the (possibly scalable) number of elements in the vector...
Type * getElementType() const
constexpr ScalarTy getFixedValue() const
Definition TypeSize.h:201
constexpr bool isScalable() const
Returns whether the quantity is scaled by a runtime quantity (vscale).
Definition TypeSize.h:169
An efficient, type-erasing, non-owning reference to a callable.
const ParentTy * getParent() const
Definition ilist_node.h:34
self_iterator getIterator()
Definition ilist_node.h:123
This class implements an extremely fast bulk output stream that can only output to a stream.
Definition raw_ostream.h:53
CallInst * Call
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
constexpr char Align[]
Key for Kernel::Arg::Metadata::mAlign.
constexpr std::underlying_type_t< E > Mask()
Get a bitmask with 1s in all places up to the high-order bit of E's largest value.
@ BasicBlock
Various leaf nodes.
Definition ISDOpcodes.h:83
LLVM_ABI StringRef getBaseName(ID id)
Return the LLVM name for an intrinsic, without encoded types for overloading, such as "llvm....
Function * Kernel
Summary of a kernel (=entry point for target offloading).
Definition OpenMPOpt.h:21
NodeAddr< FuncNode * > Func
Definition RDFGraph.h:393
friend class Instruction
Iterator for Instructions in a `BasicBlock.
Definition BasicBlock.h:73
This is an optimization pass for GlobalISel generic memory operations.
const InstrumentationOptions & getInstrumentationOptions(const LLVMContext &C)
unsigned Log2_32_Ceil(uint32_t Value)
Return the ceil log base 2 of the specified value, 32 if the value is zero.
Definition MathExtras.h:339
@ Offset
Definition DWP.cpp:577
auto size(R &&Range, std::enable_if_t< std::is_base_of< std::random_access_iterator_tag, typename std::iterator_traits< decltype(Range.begin())>::iterator_category >::value, void > *=nullptr)
Get the size of a range.
Definition STLExtras.h:1685
RelativeUniformCounterPtr Values
Definition InstrProf.h:91
auto enumerate(FirstRange &&First, RestRanges &&...Rest)
Given two or more input ranges, returns a new range whose values are tuples (A, B,...
Definition STLExtras.h:2575
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
@ Done
Definition Threading.h:60
bool isAligned(Align Lhs, uint64_t SizeInBytes)
Checks that SizeInBytes is a multiple of the alignment.
Definition Alignment.h:139
@ Store
The extracted value is stored (ExtractElement only).
LLVM_ABI std::pair< Instruction *, Value * > SplitBlockAndInsertSimpleForLoop(Value *End, BasicBlock::iterator SplitBefore)
Insert a for (int i = 0; i < End; i++) loop structure (with the exception that End is assumed > 0,...
InnerAnalysisManagerProxy< FunctionAnalysisManager, Module > FunctionAnalysisManagerModuleProxy
Provide the FunctionAnalysisManager to Module proxy.
constexpr bool isPowerOf2_64(uint64_t Value)
Return true if the argument is a power of two > 0 (64 bit edition.)
Definition MathExtras.h:285
unsigned Log2_64(uint64_t Value)
Return the floor log base 2 of the specified value, -1 if the value is zero.
Definition MathExtras.h:332
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Value
Definition InstrProf.h:143
LLVM_ABI bool removeUnreachableBlocks(Function &F, DomTreeUpdater *DTU=nullptr, MemorySSAUpdater *MSSAU=nullptr, bool FoldInstsToUnreachable=true)
Remove all blocks that can not be reached from the function's entry.
Definition Local.cpp:2961
auto dyn_cast_or_null(const Y &Val)
Definition Casting.h:753
LLVM_ABI std::pair< Function *, FunctionCallee > getOrCreateSanitizerCtorAndInitFunctions(Module &M, StringRef CtorName, StringRef InitName, ArrayRef< Type * > InitArgTypes, ArrayRef< Value * > InitArgs, function_ref< void(Function *, FunctionCallee)> FunctionsCreatedCallback, StringRef VersionCheckName=StringRef(), bool Weak=false)
Creates sanitizer constructor function lazily.
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:209
bool none_of(R &&Range, UnaryPredicate P)
Provide wrappers to std::none_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1769
IRBuilder(LLVMContext &, FolderTy, InserterTy) -> IRBuilder< FolderTy, InserterTy >
LLVM_ABI void report_fatal_error(Error Err, bool gen_crash_diag=true)
Definition Error.cpp:163
constexpr uint64_t alignTo(uint64_t Size, Align A)
Returns a multiple of A needed to store Size bytes.
Definition Alignment.h:149
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
bool isa(const From &Val)
isa<X> - Return true if the parameter to the template is an instance of one of the template type argu...
Definition Casting.h:547
LLVM_ABI bool isKnownNonZero(const Value *V, const SimplifyQuery &Q, unsigned Depth=0)
Return true if the given value is known to be non-zero when defined.
LLVM_ABI raw_fd_ostream & errs()
This returns a reference to a raw_ostream for standard error.
AtomicOrdering
Atomic ordering for LLVM's memory model.
@ First
Helpers to iterate all locations in the MemoryEffectsBase class.
Definition ModRef.h:74
@ Or
Bitwise or logical OR of integers.
@ And
Bitwise or logical AND of integers.
@ Add
Sum of integers.
IntPtrTy
Definition InstrProf.h:82
DWARFExpression::Operation Op
RoundingMode
Rounding mode.
ArrayRef(const T &OneElt) -> ArrayRef< T >
constexpr unsigned BitWidth
LLVM_ABI void appendToGlobalCtors(Module &M, Function *F, int Priority, Constant *Data=nullptr)
Append F to the list of global ctors of module M with the given Priority.
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
constexpr bool valueOr(BoolOrDefault X, bool Default)
iterator_range< df_iterator< T > > depth_first(const T &G)
LLVM_ABI Instruction * SplitBlockAndInsertIfThen(Value *Cond, BasicBlock::iterator SplitBefore, bool Unreachable, MDNode *BranchWeights=nullptr, DomTreeUpdater *DTU=nullptr, LoopInfo *LI=nullptr, BasicBlock *ThenBlock=nullptr)
Split the containing block at the specified instruction - everything before SplitBefore stays in the ...
@ End
Run the machine verifier once, at the end of the pipeline.
Definition CodeGen.h:320
LLVM_ABI void maybeMarkSanitizerLibraryCallNoBuiltin(CallInst *CI, const TargetLibraryInfo *TLI)
Given a CallInst, check if it calls a string function known to CodeGen, and mark it with NoBuiltin if...
Definition Local.cpp:3649
LLVM_ABI bool checkIfAlreadyInstrumented(Module &M, StringRef Flag)
Check if module has flag attached, if not add the flag.
std::string itostr(int64_t X)
AnalysisManager< Module > ModuleAnalysisManager
Convenience typedef for the Module analysis manager.
Definition MIRParser.h:39
#define N
This struct is a compact representation of a valid (non-zero power of two) alignment.
Definition Alignment.h:39
constexpr uint64_t value() const
This is a hole in the type system and should not be abused.
Definition Alignment.h:82
LLVM_ABI void printPipeline(raw_ostream &OS, function_ref< StringRef(StringRef)> MapClassName2PassName)
LLVM_ABI PreservedAnalyses run(Module &M, ModuleAnalysisManager &AM)