← Back to Pull requests

[LFI][X86] Add memory access rewrites #227511

Merged
zyedidia merged 12 files (1498 lines) on Nov 10, 2026 01:39 UTC
View on GitHub
zyedidia zyedidia commented on Sep 29, 2026 23:21 UTC
Author

This adds memory access rewriting for the x86-64 LFI target using %gs as the base register for rewrites. By using 32-bit register combined with the sandbox base in %gs, memory accesses can be rewritten to be confined to an LFI sandbox with little overhead. See the documentation in LFI.md for details on exact rewrite sequences.

Diff: 1498 lines (+1443 / -55) across 12 files Reviewer: nickdesaulniers Review duration: 59177m
All Vouch review confidence checks passed
Residual risk 0.09 = Change Risk (0.59) × (1 − Review Confidence (0.84)). Review depth and reviewer attention state are adequate.
Model 1 · Change Risk (XGBoost)
Score: 0.59 · 1498 lines diff across 12 files
0.59
Model 2 · Review Depth (DistilBERT)
Depth Score: 0.84 · 5 substantive comment(s)
0.84
Model 3 · Review Timing & Attention
Session adequacy: 100% · Reviewer familiarity: 50%
84%
Bedrock Claude 3 · Risk Narration
(disconnected)
Groq
Groq Risk Narration
AWS Bedrock is currently disconnected. Generate high-confidence PR triage narration on-demand using Groq.
Model 1 · Change Risk Attribution
SHAP Weights
Diff Size diff_size
0.400
Real PR Conversation Timeline
31 items
llvmorg-github-actions[bot] llvmorg-github-actions[bot] commented on Sep 29, 2026 23:22 UTC
Bot

<!--LLVM PR SUMMARY COMMENT-->

@llvm/pr-subscribers-backend-x86

Author: Zachary Yedidia (zyedidia)

<details>
<summary>Changes</summary>

This adds memory access rewriting for the x86-64 LFI target using %gs as the base register for rewrites. By using 32-bit register combined with the sandbox base in %gs, memory accesses can be rewritten to be confined to an LFI sandbox with little overhead. See the documentation in LFI.md for details on exact rewrite sequences.

---
Full diff: https://github.com/llvm/llvm-project/pull/227511.diff

10 Files Affected:

  • (modified) llvm/docs/LFI.md (+184-14)

  • (modified) llvm/lib/Target/X86/MCTargetDesc/X86MCLFIRewriter.cpp (+478-14)

  • (modified) llvm/lib/Target/X86/MCTargetDesc/X86MCLFIRewriter.h (+43-1)

  • (added) llvm/test/CodeGen/X86/lfi-rep-string.ll (+25)

  • (modified) llvm/test/MC/X86/LFI/control-flow.s (+11-8)

  • (added) llvm/test/MC/X86/LFI/memory-errors.s (+53)

  • (added) llvm/test/MC/X86/LFI/memory.s (+158)

  • (added) llvm/test/MC/X86/LFI/stack.s (+93)

  • (added) llvm/test/MC/X86/LFI/string.s (+74)

  • (modified) llvm/test/MC/X86/LFI/thread-pointer.s (+19-19)
  • ``````

    The server is unavailable at this time. Please wait a few minutes before you try again.
    
    ``````

    </details>

    github-actions[bot] github-actions[bot] commented on Sep 29, 2026 23:25 UTC
    Bot

    <!--LLVM CODE FORMAT COMMENT: {clang-format}-->

    :white_check_mark: With the latest revision this PR passed the C/C++ code formatter.

    nickdesaulniers nickdesaulniers commented on code on Oct 08, 2026 21:44 UTC
    Code Review
    llvm/lib/Target/X86/MCTargetDesc/X86MCLFIRewriter.cpp:1
    @@ -367,23 +411,417 @@ void X86::X86MCLFIRewriter::rewriteFSAccess(const MCInst &Inst, MCStreamer &Out,
       // movq %fs:(%rdi), %rax
       // ->
       // movq 16(%r15), %rax
    -  // movq (%rax,%rdi), %rax
    +  // movq %gs:(%eax,%edi), %rax
       MCInst Modified(Inst);
       Modified.getOperand(MemIdx + X86::AddrBaseReg).setReg(TPDest);
       if (HasBase && !HasIndex)
         Modified.getOperand(MemIdx + X86::AddrIndexReg).setReg(BaseReg);
       Modified.getOperand(MemIdx + X86::AddrSegmentReg).setReg(X86::NoRegister);
    -  Out.emitInstruction(Modified, STI);
    +  doRewriteInst(Modified, Out, STI);
    +}
    +
    +// Return true if Reg always contains an address within the sandbox.
    +static bool isSandboxBaseReg(MCRegister Reg) {
    +  return Reg == LFIBaseReg || Reg == X86::RSP || Reg == X86::RIP;
    +}
    +
    +// Return true if Inst reads or writes memory through an implicit pointer
    +// register instead of an addressing mode, and so cannot be sandboxed by
    +// rewriting its operands.
    +static bool hasImplicitMemPointer(unsigned Opcode) {
    +  switch (Opcode) {
    +  // xlat loads from (%rbx,%al).
    +  case X86::XLAT:
    +  // maskmov stores to (%rdi).
    +  case X86::MASKMOVDQU:
    +  case X86::MASKMOVDQU64:
    +  case X86::VMASKMOVDQU:
    +  case X86::VMASKMOVDQU64:
    +  case X86::MMX_MASKMOVQ:
    +  case X86::MMX_MASKMOVQ64:
    +    return true;
    +  default:
    +    return false;
    +  }
    +}
    +
    +// Return true if Inst has a memory operand that is not dereferenced.
    +static bool ignoresMemOperand(unsigned Opcode) {
    +  switch (Opcode) {
    +  case X86::LEA16r:
    +  case X86::LEA32r:
    +  case X86::LEA64r:
    +  case X86::LEA64_32r:
    +  case X86::NOOPW:
    +  case X86::NOOPL:
    +  case X86::NOOPQ:
    +    return true;
    +  default:
    +    return false;
    +  }
    +}
    +
    +// Return true if the index register of the memory operand at MemIdx is a
    +// general-purpose register, and so can be truncated along with the base.
    +static bool hasGPRIndex(const MCInst &Inst, int MemIdx) {
    +  MCRegister Index = Inst.getOperand(MemIdx + X86::AddrIndexReg).getReg();
    +  return Index && (getX86MCRegisterClass(X86::GR64RegClassID).contains(Index) ||
    +                   getX86MCRegisterClass(X86::GR32RegClassID).contains(Index));
    +}
    +
    +// Rewrite the addressing mode of the memory operand at MemIdx so that the
    +// access it performs stays inside the sandbox.
    +//
    +// movq 8(%rax,%rcx,4), %rdi
    +// ->
    +// movq %gs:8(%eax,%ecx,4), %rdi
    +void X86::X86MCLFIRewriter::sandboxMemOperand(MCInst &Inst, int MemIdx) const {
    +  MCOperand &Base = Inst.getOperand(MemIdx + X86::AddrBaseReg);
    +  MCOperand &Index = Inst.getOperand(MemIdx + X86::AddrIndexReg);
    +  MCOperand &Segment = Inst.getOperand(MemIdx + X86::AddrSegmentReg);
    +
    +  // A base register that always points into the sandbox needs no rewriting, as
    +  // long as there is no index register.
    +  if (isSandboxBaseReg(Base.getReg()) && !Index.getReg())
    +    return;
    +
    +  // An absolute address has no register to truncate, so make it relative to
    +  // the sandbox base instead.
    +  if (!Base.getReg() && !Index.getReg()) {
    +    Base.setReg(LFIBaseReg);
    +    return;
    +  }
    +
    +  // If there is no Base and the Index is not a GPR, then we use r14d (all
    +  // zeroes) as the base for the rewritten addressing mode.
    +  bool GPRIndex = hasGPRIndex(Inst, MemIdx);
    +
    +  Segment.setReg(LFIBaseSeg);
    +  if (Base.getReg())
    +    Base.setReg(getReg32(Base.getReg()));
    +  else if (!GPRIndex)
    +    Base.setReg(getReg32(LFIBaseReg));
    +  if (GPRIndex)
    +    Index.setReg(getReg32(Index.getReg()));
    +}
    +
    +void X86::X86MCLFIRewriter::sandboxMemAccess(MCInst &Inst) const {
    +  if (ignoresMemOperand(Inst.getOpcode()))
    +    return;
    +
    +  int MemIdx = X86II::getMemoryOperandIdx(InstInfo->get(Inst.getOpcode()));
    +  if (MemIdx >= 0)
    +    sandboxMemOperand(Inst, MemIdx);
    +}
    +
    +void X86::X86MCLFIRewriter::rewriteMemAccess(const MCInst &Inst,
    +                                             MCStreamer &Out,
    +                                             const MCSubtargetInfo &STI) {
    +  const MCInstrDesc &Desc = InstInfo->get(Inst.getOpcode());
    +
    +  // The moffs form of mov encodes an absolute address in the instruction
    +  // instead of an addressing mode, so it is unsupported.
    +  if ((Desc.TSFlags & X86II::FormMask) == X86II::RawFrmMemOffs ||
    +      hasImplicitMemPointer(Inst.getOpcode()))
    +    return error(Inst, "unsupported memory access");
    +
    +  MCInst Sandboxed(Inst);
    +  sandboxMemAccess(Sandboxed);
    +  emitWithPrefixes(Sandboxed, Out, STI);
    +}
    +
    +namespace {
    +struct StringOpPointers {
    +  bool UsesDest;
    +  bool UsesSrc;
    +};
    +} // namespace
    +
    +static std::optional<StringOpPointers> getStringOpPointers(unsigned Opcode) {
    +  switch (Opcode) {
    +  case X86::STOSB:
    +  case X86::STOSW:
    +  case X86::STOSL:
    +  case X86::STOSQ:
    +  case X86::REP_STOSB_64:
    +  case X86::REP_STOSW_64:
    +  case X86::REP_STOSD_64:
    +  case X86::REP_STOSQ_64:
    +  case X86::SCASB:
    +  case X86::SCASW:
    +  case X86::SCASL:
    +  case X86::SCASQ:
    +    return StringOpPointers{true, false};
    +  case X86::MOVSB:
    +  case X86::MOVSW:
    +  case X86::MOVSL:
    +  case X86::MOVSQ:
    +  case X86::REP_MOVSB_64:
    +  case X86::REP_MOVSW_64:
    +  case X86::REP_MOVSD_64:
    +  case X86::REP_MOVSQ_64:
    +  case X86::CMPSB:
    +  case X86::CMPSW:
    +  case X86::CMPSL:
    +  case X86::CMPSQ:
    +    return StringOpPointers{true, true};
    +  case X86::LODSB:
    +  case X86::LODSW:
    +  case X86::LODSL:
    +  case X86::LODSQ:
    +    return StringOpPointers{false, true};
    +  default:
    +    return std::nullopt;
    +  }
    +}
    +
    +static void emitStringPtrFixup(MCRegister Reg, MCRegister Reg32,
    +                               MCStreamer &Out, const MCSubtargetInfo &STI) {
    +  Out.emitInstruction(MCInstBuilder(X86::MOV32rr).addReg(Reg32).addReg(Reg32),
    +                      STI);
    +
    +  Out.emitInstruction(MCInstBuilder(X86::LEA64r)
    +                          .addReg(Reg)
    +                          .addReg(LFIBaseReg)
    +                          .addImm(1)
    +                          .addReg(Reg)
    +                          .addImm(0)
    +                          .addReg(X86::NoRegister),
    +                      STI);
    +}
    +
    +// rep movsq
    +// ->
    +// .bundle_lock
    +// movl %edi, %edi
    +// leaq (%r14,%rdi), %rdi
    +// movl %esi, %esi
    +// leaq (%r14,%rsi), %rsi
    +// rep movsq
    +// .bundle_unlock
    +void X86::X86MCLFIRewriter::rewriteStringOperation(const MCInst &Inst,
    +                                                   MCStreamer &Out,
    +                                                   const MCSubtargetInfo &STI) {
    +  std::optional<StringOpPointers> Ptrs = getStringOpPointers(Inst.getOpcode());
    +  assert(Ptrs);

    Do not assert without an error message.

    nickdesaulniers nickdesaulniers commented on code on Oct 08, 2026 21:45 UTC
    Code Review
    llvm/lib/Target/X86/MCTargetDesc/X86MCLFIRewriter.cpp:1
    @@ -28,10 +30,18 @@ static constexpr MCRegister LFIBaseReg = X86::R14;
     static constexpr MCRegister LFIScratchReg = X86::R11;
     static constexpr MCRegister LFITPReg = X86::R15;
     
    +// Segment register whose base always holds the sandbox base address.
    +static constexpr MCRegister LFIBaseSeg = X86::GS;
    +
     // Byte offset into the context register file (pointed to by R15) where the
     // thread pointer is stored.
     static constexpr int TPOffset = 16;
     
    +static bool isPrefix(const MCInst &Inst, const MCInstrInfo &InstInfo) {
    +  return (InstInfo.get(Inst.getOpcode()).TSFlags & X86II::FormMask) ==
    +         X86II::PrefixByte;

    Is this equivalent?

      return X86II::isPrefix(InstInfo.get(Inst.getOpcode()).TSFlags);
    

    nickdesaulniers nickdesaulniers commented on code on Oct 08, 2026 21:48 UTC
    Code Review
    llvm/test/MC/X86/LFI/memory.s:1
    @@ -0,0 +1,158 @@
    +// RUN: llvm-mc -triple x86_64_lfi %s | FileCheck %s
    +
    +movq (%rax), %rdi
    +// CHECK: movq %gs:(%eax), %rdi
    +
    +movq %rcx, (%rax)
    +// CHECK: movq %rcx, %gs:(%eax)
    +
    +movq 8(%rax), %rdi
    +// CHECK: movq %gs:8(%eax), %rdi
    +
    +movq -8(%rax), %rdi
    +// CHECK: movq %gs:-8(%eax), %rdi
    +
    +movq (%rax,%rdi), %rcx
    +// CHECK: movq %gs:(%eax,%edi), %rcx
    +
    +movq 16(%rax,%rdi,4), %rcx
    +// CHECK: movq %gs:16(%eax,%edi,4), %rcx
    +
    +movq (,%rdi,8), %rcx
    +// CHECK: movq %gs:(,%edi,8), %rcx
    +
    +movl (%rax), %edi
    +// CHECK: movl %gs:(%eax), %edi
    +
    +movw (%rax), %di
    +// CHECK: movw %gs:(%eax), %di
    +
    +movb (%rax), %dil
    +// CHECK: movb %gs:(%eax), %dil
    +
    +movb (%rax), %ah
    +// CHECK: movb %gs:(%eax), %ah
    +
    +// An address that is already 32-bit keeps its registers.
    +
    +movl (%edi), %eax
    +// CHECK: movl %gs:(%edi), %eax
    +
    +addq $1, (%rax)
    +// CHECK: addq $1, %gs:(%eax)
    +
    +incq (%rax)
    +// CHECK: incq %gs:(%eax)
    +
    +xchgq %rax, (%rcx)
    +// CHECK: xchgq %rax, %gs:(%ecx)
    +
    +lock incq (%rax)
    +// CHECK: lock {{.*}}incq %gs:(%eax)
    +
    +lock
    +addq $1, (%rax)
    +// CHECK:      lock
    +// CHECK-NEXT: addq $1, %gs:(%eax)
    +
    +movq (%rsp), %rax
    +// CHECK: movq (%rsp), %rax
    +
    +movq 8(%rsp), %rax
    +// CHECK: movq 8(%rsp), %rax
    +
    +movq %rax, -8(%rsp)
    +// CHECK: movq %rax, -8(%rsp)
    +
    +movq foo(%rip), %rax
    +// CHECK: movq foo(%rip), %rax
    +
    +movq %rax, foo(%rip)
    +// CHECK: movq %rax, foo(%rip)
    +
    +movq (%r14), %rax
    +// CHECK: movq (%r14), %rax
    +
    +movq 8(%r14), %rax
    +// CHECK: movq 8(%r14), %rax
    +
    +movq (%rsp,%rax), %rcx
    +// CHECK: movq %gs:(%esp,%eax), %rcx
    +
    +movq (%r14,%rax), %rcx
    +// CHECK: movq %gs:(%r14d,%eax), %rcx
    +
    +movq 4096, %rax
    +// CHECK: movq 4096(%r14), %rax
    +
    +vextractf64x2 $1, %zmm0, (%rax)
    +// CHECK: vextractf64x2 $1, %zmm0, %gs:(%eax)
    +
    +vextracti32x8 $1, %zmm0, 16(%rax,%rcx,4)
    +// CHECK: vextracti32x8 $1, %zmm0, %gs:16(%eax,%ecx,4)
    +
    +tileloaddrs 291(%rbp,%rax,4), %tmm3
    +// CHECK: tileloaddrs %gs:291(%ebp,%eax,4), %tmm3
    +
    +movq (%rax,%riz,1), %rbx
    +// CHECK: movq %gs:(%eax,%riz), %rbx
    +
    +movq (,%riz,1), %rbx
    +// CHECK: movq %gs:(%r14d,%riz), %rbx
    +
    +leaq (%rax), %rdi
    +// CHECK: leaq (%rax), %rdi
    +
    +leaq 8(%rax,%rcx,4), %rdi
    +// CHECK: leaq 8(%rax,%rcx,4), %rdi
    +
    +leal 4(%eax), %edx
    +// CHECK: leal 4(%eax), %edx
    +
    +nopw (%rax)
    +// CHECK: nopw (%rax)
    +
    +nopl (%rax,%rcx,4)
    +// CHECK: nopl (%rax,%rcx,4)
    +
    +movaps (%rdi), %xmm0
    +// CHECK: movaps %gs:(%edi), %xmm0
    +
    +movups %xmm1, 16(%rsi,%rdx,4)
    +// CHECK: movups %xmm1, %gs:16(%esi,%edx,4)
    +
    +flds (%rax)
    +// CHECK: flds %gs:(%eax)
    +
    +fstpl 8(%rsp)
    +// CHECK: fstpl 8(%rsp)
    +
    +vgatherdpd %xmm3, (%rax,%xmm2,8), %xmm0
    +// CHECK: vgatherdpd %xmm3, %gs:(%eax,%xmm2,8), %xmm0
    +
    +vgatherqps %xmm3, (%rdi,%xmm2,4), %xmm0
    +// CHECK: vgatherqps %xmm3, %gs:(%edi,%xmm2,4), %xmm0
    +
    +vpgatherdd (%rax,%ymm2,4), %ymm0 {%k1}
    +// CHECK: vpgatherdd %gs:(%eax,%ymm2,4), %ymm0 {%k1}
    +
    +vpscatterdd %ymm0, 16(%rax,%ymm2,4) {%k1}
    +// CHECK: vpscatterdd %ymm0, %gs:16(%eax,%ymm2,4) {%k1}
    +
    +vgatherpf0dps (%rax,%zmm2,4) {%k1}
    +// CHECK: vgatherpf0dps %gs:(%eax,%zmm2,4) {%k1}
    +
    +vgatherdpd %xmm3, (,%xmm2,8), %xmm0
    +// CHECK: vgatherdpd %xmm3, %gs:(%r14d,%xmm2,8), %xmm0
    +
    +vgatherdpd %xmm3, (%r14,%xmm2,8), %xmm0
    +// CHECK: vgatherdpd %xmm3, %gs:(%r14d,%xmm2,8), %xmm0
    +
    +pushq %rax
    +// CHECK: pushq %rax
    +
    +pushq (%rax)
    +// CHECK: pushq %gs:(%eax)
    +
    +popq (%rax)
    +// CHECK: popq %gs:(%eax)

    Please add tests for:

    movq (%rax,%riz,1), %rbx
    movq (,%riz,1), %rbx
    movq foo(%eip), %rax
    

    nickdesaulniers nickdesaulniers commented on code on Oct 08, 2026 21:50 UTC
    Code Review
    llvm/test/MC/X86/LFI/memory-errors.s:1
    @@ -0,0 +1,53 @@
    +// RUN: not llvm-mc -triple x86_64_lfi %s 2>&1 | FileCheck %s
    +
    +movq %gs:(%rax), %rbx
    +// CHECK: error: invalid use of reserved segment register %gs
    +
    +movq %gs:8, %rbx
    +// CHECK: error: invalid use of reserved segment register %gs
    +
    +movw %ax, %gs
    +// CHECK: error: illegal modification of reserved LFI register
    +
    +wrgsbase %rax
    +// CHECK: error: illegal modification of reserved segment base
    +
    +wrgsbasel %eax
    +// CHECK: error: illegal modification of reserved segment base
    +
    +wrfsbase %rax
    +// CHECK: error: illegal modification of reserved segment base
    +
    +wrfsbasel %eax
    +// CHECK: error: illegal modification of reserved segment base
    +
    +movabsq 0x123456789abcdef, %rax
    +// CHECK: error: unsupported memory access
    +
    +movabsb %al, 0x123456789abcdef
    +// CHECK: error: unsupported memory access
    +
    +xlatb
    +// CHECK: error: unsupported memory access
    +
    +maskmovdqu %xmm1, %xmm0
    +// CHECK: error: unsupported memory access
    +
    +xchgq %rax, %rsp
    +// CHECK: error: unsupported modification of the stack pointer
    +
    +shlq $1, %rsp
    +// CHECK: error: unsupported modification of the stack pointer
    +
    +movw %ax, %sp
    +// CHECK: error: unsupported modification of the stack pointer
    +
    +.code32
    +
    +lock
    +// CHECK: error: LFI only supports 64-bit mode
    +
    +.code64
    +
    +lock
    +// CHECK: error: unsupported instruction prefix

    Please add tests for:

    gs movq (%rsp), %rax
    fs movq (%rsp), %rax
    addr32 movq (%rsp), %rax
    rex64 movq %rdi, %rsp
    data16 addq $8, %rsp
    lock jmpq *(%rdi)
    movsq (%esi), %es:(%edi)
    movsq %fs:(%rsi), %es:(%rdi)
    xchgl %eax, %esp
    shll $1, %esp
    enter $16, $2
    

    github-actions[bot] github-actions[bot] commented on Oct 20, 2026 11:50 UTC
    Bot

    <!--PREMERGE ADVISOR COMMENT: Linux-->

    :penguin: Linux x64 Test Results

    181322 tests passed
    4277 tests skipped

    :white_check_mark: The build succeeded and all tests passed.

    nickdesaulniers nickdesaulniers commented on code on Oct 20, 2026 17:48 UTC
    Code Review
    llvm/lib/Target/X86/MCTargetDesc/X86MCLFIRewriter.cpp:1
    @@ -28,10 +30,30 @@ static constexpr MCRegister LFIBaseReg = X86::R14;
     static constexpr MCRegister LFIScratchReg = X86::R11;
     static constexpr MCRegister LFITPReg = X86::R15;
     
    +// Segment register whose base always holds the sandbox base address.
    +static constexpr MCRegister LFIBaseSeg = X86::GS;
    +
     // Byte offset into the context register file (pointed to by R15) where the
     // thread pointer is stored.
     static constexpr int TPOffset = 16;
     
    +static bool isPrefix(const MCInst &Inst, const MCInstrInfo &InstInfo) {
    +  return X86II::isPrefix(InstInfo.get(Inst.getOpcode()).TSFlags);
    +}
    +
    +// Return true if Inst is an unsupported stand-alone prefix.
    +static bool isUnsupportedPrefix(const MCInst &Inst) {

    bikeshed on the naming; functions that return bool are less readable when framed in the negative when they get negated on the caller; the reader has to double negate them in their head.

    i.e if you rename this to isSupportedPrefix, invert the return values as written, then negate in the callers I think it's more readable.

    nickdesaulniers nickdesaulniers commented on code on Oct 20, 2026 17:49 UTC
    Code Review
    llvm/lib/Target/X86/MCTargetDesc/X86MCLFIRewriter.cpp:1
    @@ -56,6 +78,18 @@ static bool isSupportedIndirectBranch(const MCInst &Inst) {
       }
     }
     
    +static bool writesSegmentBase(unsigned Opcode) {

    naming nit: isWriteSegmentBase

    nickdesaulniers nickdesaulniers commented on code on Oct 20, 2026 17:52 UTC
    Code Review
    llvm/lib/Target/X86/MCTargetDesc/X86MCLFIRewriter.cpp:1
    @@ -367,23 +427,469 @@ void X86::X86MCLFIRewriter::rewriteFSAccess(const MCInst &Inst, MCStreamer &Out,
       // movq %fs:(%rdi), %rax
       // ->
       // movq 16(%r15), %rax
    -  // movq (%rax,%rdi), %rax
    +  // movq %gs:(%eax,%edi), %rax
       MCInst Modified(Inst);
       Modified.getOperand(MemIdx + X86::AddrBaseReg).setReg(TPDest);
       if (HasBase && !HasIndex)
         Modified.getOperand(MemIdx + X86::AddrIndexReg).setReg(BaseReg);
       Modified.getOperand(MemIdx + X86::AddrSegmentReg).setReg(X86::NoRegister);
    -  Out.emitInstruction(Modified, STI);
    +  doRewriteInst(Modified, Out, STI);
    +}
    +
    +// Return true if Reg always contains an address within the sandbox.
    +static bool isSandboxBaseReg(MCRegister Reg) {
    +  return Reg == LFIBaseReg || Reg == X86::RSP || Reg == X86::RIP;
    +}
    +
    +// Return true if Inst reads or writes memory through a pointer register
    +// instead of an addressing mode, and so cannot be sandboxed by rewriting its
    +// operands.
    +static bool hasImplicitMemPointer(unsigned Opcode) {
    +  switch (Opcode) {
    +  // xlat loads from (%rbx,%al).
    +  case X86::XLAT:
    +  // maskmov stores to (%rdi).
    +  case X86::MASKMOVDQU:
    +  case X86::MASKMOVDQU64:
    +  case X86::VMASKMOVDQU:
    +  case X86::VMASKMOVDQU64:
    +  case X86::MMX_MASKMOVQ:
    +  case X86::MMX_MASKMOVQ64:
    +  // clzero zeroes the cache line at (%rax).
    +  case X86::CLZERO32r:
    +  case X86::CLZERO64r:
    +  // movdir64b and enqcmd store to the address in their register operand.
    +  case X86::MOVDIR64B32:
    +  case X86::MOVDIR64B64:
    +  case X86::MOVDIR64B32_EVEX:
    +  case X86::MOVDIR64B64_EVEX:
    +  case X86::ENQCMD32:
    +  case X86::ENQCMD64:
    +  case X86::ENQCMD32_EVEX:
    +  case X86::ENQCMD64_EVEX:
    +  case X86::ENQCMDS32:
    +  case X86::ENQCMDS64:
    +  case X86::ENQCMDS32_EVEX:
    +  case X86::ENQCMDS64_EVEX:
    +    return true;
    +  default:
    +    return false;
    +  }
    +}
    +
    +// Return true if Inst has a memory operand that is not dereferenced.
    +static bool ignoresMemOperand(unsigned Opcode) {
    +  switch (Opcode) {
    +  case X86::LEA16r:
    +  case X86::LEA32r:
    +  case X86::LEA64r:
    +  case X86::LEA64_32r:
    +  case X86::NOOPW:
    +  case X86::NOOPL:
    +  case X86::NOOPQ:
    +    return true;
    +  default:
    +    return false;
    +  }
    +}
    +
    +// Return true if the index register of the memory operand at MemIdx is a
    +// general-purpose register, and so can be truncated along with the base.
    +static bool hasGPRIndex(const MCInst &Inst, int MemIdx) {
    +  MCRegister Index = Inst.getOperand(MemIdx + X86::AddrIndexReg).getReg();
    +  return Index && getX86MCRegisterClass(X86::GR64RegClassID).contains(Index);
    +}
    +
    +// Return true if the memory operand at MemIdx uses a 32-bit address size,
    +// which is selected by a 32-bit base or index register.
    +static bool has32BitAddress(const MCInst &Inst, int MemIdx) {
    +  MCRegister Base = Inst.getOperand(MemIdx + X86::AddrBaseReg).getReg();
    +  MCRegister Index = Inst.getOperand(MemIdx + X86::AddrIndexReg).getReg();
    +  const MCRegisterClass &GR32 = getX86MCRegisterClass(X86::GR32RegClassID);
    +  return Base == X86::EIP || GR32.contains(Base) || Index == X86::EIZ ||
    +         GR32.contains(Index);
    +}
    +
    +// Rewrite the addressing mode of the memory operand at MemIdx so that the
    +// access it performs stays inside the sandbox.
    +//
    +// movq 8(%rax,%rcx,4), %rdi
    +// ->
    +// movq %gs:8(%eax,%ecx,4), %rdi
    +void X86::X86MCLFIRewriter::sandboxMemOperand(MCInst &Inst, int MemIdx) const {
    +  MCOperand &Base = Inst.getOperand(MemIdx + X86::AddrBaseReg);
    +  MCOperand &Scale = Inst.getOperand(MemIdx + X86::AddrScaleAmt);
    +  MCOperand &Index = Inst.getOperand(MemIdx + X86::AddrIndexReg);
    +  MCOperand &Segment = Inst.getOperand(MemIdx + X86::AddrSegmentReg);
    +
    +  // %riz only encodes the absence of an index register, so drop it and handle
    +  // the access as one without an index.
    +  if (Index.getReg() == X86::RIZ) {
    +    Index.setReg(X86::NoRegister);
    +    Scale.setImm(1);
    +  }
    +
    +  // A base register that always points into the sandbox needs no rewriting, as
    +  // long as there is no index register.
    +  if (isSandboxBaseReg(Base.getReg()) && !Index.getReg())
    +    return;
    +
    +  // An absolute address has no register to truncate, so make it relative to
    +  // the sandbox base instead.
    +  if (!Base.getReg() && !Index.getReg()) {
    +    Base.setReg(LFIBaseReg);
    +    return;
    +  }
    +
    +  // If there is no Base and the Index is not a GPR, then we use r14d (all
    +  // zeroes) as the base for the rewritten addressing mode.
    +  bool GPRIndex = hasGPRIndex(Inst, MemIdx);
    +
    +  Segment.setReg(LFIBaseSeg);
    +  if (Base.getReg())
    +    Base.setReg(getReg32(Base.getReg()));
    +  else if (!GPRIndex)
    +    Base.setReg(getReg32(LFIBaseReg));
    +  if (GPRIndex)
    +    Index.setReg(getReg32(Index.getReg()));
    +}
    +
    +void X86::X86MCLFIRewriter::sandboxMemAccess(MCInst &Inst) const {
    +  if (ignoresMemOperand(Inst.getOpcode()))
    +    return;
    +
    +  int MemIdx = X86II::getMemoryOperandIdx(InstInfo->get(Inst.getOpcode()));
    +  if (MemIdx >= 0)
    +    sandboxMemOperand(Inst, MemIdx);
    +}
    +
    +void X86::X86MCLFIRewriter::rewriteMemAccess(const MCInst &Inst,
    +                                             MCStreamer &Out,
    +                                             const MCSubtargetInfo &STI) {
    +  const MCInstrDesc &Desc = InstInfo->get(Inst.getOpcode());
    +
    +  // The moffs form of mov encodes an absolute address in the instruction
    +  // instead of an addressing mode, so it is unsupported.
    +  if ((Desc.TSFlags & X86II::FormMask) == X86II::RawFrmMemOffs ||
    +      hasImplicitMemPointer(Inst.getOpcode()))
    +    return error(Inst, "unsupported memory access");
    +
    +  MCInst Sandboxed(Inst);
    +  sandboxMemAccess(Sandboxed);
    +  emitWithPrefixes(Sandboxed, Out, STI);
    +}
    +
    +namespace {
    +struct StringOpPointers {
    +  bool UsesDest;
    +  bool UsesSrc;
    +};
    +} // namespace
    +
    +static std::optional<StringOpPointers> getStringOpPointers(unsigned Opcode) {
    +  switch (Opcode) {
    +  case X86::STOSB:
    +  case X86::STOSW:
    +  case X86::STOSL:
    +  case X86::STOSQ:
    +  case X86::REP_STOSB_64:
    +  case X86::REP_STOSW_64:
    +  case X86::REP_STOSD_64:
    +  case X86::REP_STOSQ_64:
    +  case X86::SCASB:
    +  case X86::SCASW:
    +  case X86::SCASL:
    +  case X86::SCASQ:
    +    return StringOpPointers{true, false};
    +  case X86::MOVSB:
    +  case X86::MOVSW:
    +  case X86::MOVSL:
    +  case X86::MOVSQ:
    +  case X86::REP_MOVSB_64:
    +  case X86::REP_MOVSW_64:
    +  case X86::REP_MOVSD_64:
    +  case X86::REP_MOVSQ_64:
    +  case X86::CMPSB:
    +  case X86::CMPSW:
    +  case X86::CMPSL:
    +  case X86::CMPSQ:
    +    return StringOpPointers{true, true};
    +  case X86::LODSB:
    +  case X86::LODSW:
    +  case X86::LODSL:
    +  case X86::LODSQ:
    +    return StringOpPointers{false, true};
    +  default:
    +    return std::nullopt;
    +  }
    +}
    +
    +static void emitStringPtrFixup(MCRegister Reg, MCRegister Reg32,
    +                               MCStreamer &Out, const MCSubtargetInfo &STI) {
    +  Out.emitInstruction(MCInstBuilder(X86::MOV32rr).addReg(Reg32).addReg(Reg32),
    +                      STI);
    +
    +  Out.emitInstruction(MCInstBuilder(X86::LEA64r)
    +                          .addReg(Reg)
    +                          .addReg(LFIBaseReg)
    +                          .addImm(1)
    +                          .addReg(Reg)
    +                          .addImm(0)
    +                          .addReg(X86::NoRegister),
    +                      STI);
    +}
    +
    +// rep movsq
    +// ->
    +// .bundle_lock
    +// movl %edi, %edi
    +// leaq (%r14,%rdi), %rdi
    +// movl %esi, %esi
    +// leaq (%r14,%rsi), %rsi
    +// rep movsq
    +// .bundle_unlock
    +void X86::X86MCLFIRewriter::rewriteStringOperation(const MCInst &Inst,
    +                                                   MCStreamer &Out,
    +                                                   const MCSubtargetInfo &STI) {
    +  std::optional<StringOpPointers> Ptrs = getStringOpPointers(Inst.getOpcode());
    +  assert(Ptrs && "expected a string instruction");
    +
    +  // The guards below sandbox the full 64-bit %rdi and %rsi, so the access must
    +  // use them with a 64-bit address size and no %fs segment override.
    +  for (const MCOperand &Op : Inst) {
    +    if (!Op.isReg())
    +      continue;
    +    if (Op.getReg() == X86::EDI || Op.getReg() == X86::ESI)
    +      return error(Inst, "unsupported address size for string instruction");
    +    if (Op.getReg() == X86::FS)
    +      return error(Inst, "unsupported segment override for string instruction");
    +  }
    +
    +  Out.emitBundleLock(/*AlignToEnd=*/false, STI);
    +
    +  if (Ptrs->UsesDest)
    +    emitStringPtrFixup(X86::RDI, X86::EDI, Out, STI);
    +  if (Ptrs->UsesSrc)
    +    emitStringPtrFixup(X86::RSI, X86::ESI, Out, STI);
    +
    +  emitWithPrefixes(Inst, Out, STI);
    +
    +  Out.emitBundleUnlock(STI);
    +}
    +
    +// The register form of an instruction that modifies the stack and reads its
    +// source from memory, or 0 if there is none.
    +static unsigned memToRegOpcode(unsigned Opcode) {
    +  switch (Opcode) {
    +  case X86::MOV64rm:
    +    return X86::MOV64rr;
    +  case X86::ADD64rm:
    +    return X86::ADD64rr;
    +  case X86::SUB64rm:
    +    return X86::SUB64rr;
    +  case X86::AND64rm:
    +    return X86::AND64rr;
    +  case X86::OR64rm:
    +    return X86::OR64rr;
    +  case X86::XOR64rm:
    +    return X86::XOR64rr;
    +  default:
    +    return 0;
    +  }
    +}
    +
    +// The 32-bit form of a 64-bit instruction, or 0 if the instruction has no
    +// 32-bit form that can be used to modify the stack pointer.
    +static unsigned demote64BitOpcode(unsigned Opcode) {

    Consider returning a std::optional<unsigned> here instead.

    nickdesaulniers nickdesaulniers commented on code on Oct 20, 2026 17:52 UTC
    Code Review
    llvm/lib/Target/X86/MCTargetDesc/X86MCLFIRewriter.cpp:1
    @@ -367,23 +427,469 @@ void X86::X86MCLFIRewriter::rewriteFSAccess(const MCInst &Inst, MCStreamer &Out,
       // movq %fs:(%rdi), %rax
       // ->
       // movq 16(%r15), %rax
    -  // movq (%rax,%rdi), %rax
    +  // movq %gs:(%eax,%edi), %rax
       MCInst Modified(Inst);
       Modified.getOperand(MemIdx + X86::AddrBaseReg).setReg(TPDest);
       if (HasBase && !HasIndex)
         Modified.getOperand(MemIdx + X86::AddrIndexReg).setReg(BaseReg);
       Modified.getOperand(MemIdx + X86::AddrSegmentReg).setReg(X86::NoRegister);
    -  Out.emitInstruction(Modified, STI);
    +  doRewriteInst(Modified, Out, STI);
    +}
    +
    +// Return true if Reg always contains an address within the sandbox.
    +static bool isSandboxBaseReg(MCRegister Reg) {
    +  return Reg == LFIBaseReg || Reg == X86::RSP || Reg == X86::RIP;
    +}
    +
    +// Return true if Inst reads or writes memory through a pointer register
    +// instead of an addressing mode, and so cannot be sandboxed by rewriting its
    +// operands.
    +static bool hasImplicitMemPointer(unsigned Opcode) {
    +  switch (Opcode) {
    +  // xlat loads from (%rbx,%al).
    +  case X86::XLAT:
    +  // maskmov stores to (%rdi).
    +  case X86::MASKMOVDQU:
    +  case X86::MASKMOVDQU64:
    +  case X86::VMASKMOVDQU:
    +  case X86::VMASKMOVDQU64:
    +  case X86::MMX_MASKMOVQ:
    +  case X86::MMX_MASKMOVQ64:
    +  // clzero zeroes the cache line at (%rax).
    +  case X86::CLZERO32r:
    +  case X86::CLZERO64r:
    +  // movdir64b and enqcmd store to the address in their register operand.
    +  case X86::MOVDIR64B32:
    +  case X86::MOVDIR64B64:
    +  case X86::MOVDIR64B32_EVEX:
    +  case X86::MOVDIR64B64_EVEX:
    +  case X86::ENQCMD32:
    +  case X86::ENQCMD64:
    +  case X86::ENQCMD32_EVEX:
    +  case X86::ENQCMD64_EVEX:
    +  case X86::ENQCMDS32:
    +  case X86::ENQCMDS64:
    +  case X86::ENQCMDS32_EVEX:
    +  case X86::ENQCMDS64_EVEX:
    +    return true;
    +  default:
    +    return false;
    +  }
    +}
    +
    +// Return true if Inst has a memory operand that is not dereferenced.
    +static bool ignoresMemOperand(unsigned Opcode) {
    +  switch (Opcode) {
    +  case X86::LEA16r:
    +  case X86::LEA32r:
    +  case X86::LEA64r:
    +  case X86::LEA64_32r:
    +  case X86::NOOPW:
    +  case X86::NOOPL:
    +  case X86::NOOPQ:
    +    return true;
    +  default:
    +    return false;
    +  }
    +}
    +
    +// Return true if the index register of the memory operand at MemIdx is a
    +// general-purpose register, and so can be truncated along with the base.
    +static bool hasGPRIndex(const MCInst &Inst, int MemIdx) {
    +  MCRegister Index = Inst.getOperand(MemIdx + X86::AddrIndexReg).getReg();
    +  return Index && getX86MCRegisterClass(X86::GR64RegClassID).contains(Index);
    +}
    +
    +// Return true if the memory operand at MemIdx uses a 32-bit address size,
    +// which is selected by a 32-bit base or index register.
    +static bool has32BitAddress(const MCInst &Inst, int MemIdx) {
    +  MCRegister Base = Inst.getOperand(MemIdx + X86::AddrBaseReg).getReg();
    +  MCRegister Index = Inst.getOperand(MemIdx + X86::AddrIndexReg).getReg();
    +  const MCRegisterClass &GR32 = getX86MCRegisterClass(X86::GR32RegClassID);
    +  return Base == X86::EIP || GR32.contains(Base) || Index == X86::EIZ ||
    +         GR32.contains(Index);
    +}
    +
    +// Rewrite the addressing mode of the memory operand at MemIdx so that the
    +// access it performs stays inside the sandbox.
    +//
    +// movq 8(%rax,%rcx,4), %rdi
    +// ->
    +// movq %gs:8(%eax,%ecx,4), %rdi
    +void X86::X86MCLFIRewriter::sandboxMemOperand(MCInst &Inst, int MemIdx) const {
    +  MCOperand &Base = Inst.getOperand(MemIdx + X86::AddrBaseReg);
    +  MCOperand &Scale = Inst.getOperand(MemIdx + X86::AddrScaleAmt);
    +  MCOperand &Index = Inst.getOperand(MemIdx + X86::AddrIndexReg);
    +  MCOperand &Segment = Inst.getOperand(MemIdx + X86::AddrSegmentReg);
    +
    +  // %riz only encodes the absence of an index register, so drop it and handle
    +  // the access as one without an index.
    +  if (Index.getReg() == X86::RIZ) {
    +    Index.setReg(X86::NoRegister);
    +    Scale.setImm(1);
    +  }
    +
    +  // A base register that always points into the sandbox needs no rewriting, as
    +  // long as there is no index register.
    +  if (isSandboxBaseReg(Base.getReg()) && !Index.getReg())
    +    return;
    +
    +  // An absolute address has no register to truncate, so make it relative to
    +  // the sandbox base instead.
    +  if (!Base.getReg() && !Index.getReg()) {
    +    Base.setReg(LFIBaseReg);
    +    return;
    +  }
    +
    +  // If there is no Base and the Index is not a GPR, then we use r14d (all
    +  // zeroes) as the base for the rewritten addressing mode.
    +  bool GPRIndex = hasGPRIndex(Inst, MemIdx);
    +
    +  Segment.setReg(LFIBaseSeg);
    +  if (Base.getReg())
    +    Base.setReg(getReg32(Base.getReg()));
    +  else if (!GPRIndex)
    +    Base.setReg(getReg32(LFIBaseReg));
    +  if (GPRIndex)
    +    Index.setReg(getReg32(Index.getReg()));
    +}
    +
    +void X86::X86MCLFIRewriter::sandboxMemAccess(MCInst &Inst) const {
    +  if (ignoresMemOperand(Inst.getOpcode()))
    +    return;
    +
    +  int MemIdx = X86II::getMemoryOperandIdx(InstInfo->get(Inst.getOpcode()));
    +  if (MemIdx >= 0)
    +    sandboxMemOperand(Inst, MemIdx);
    +}
    +
    +void X86::X86MCLFIRewriter::rewriteMemAccess(const MCInst &Inst,
    +                                             MCStreamer &Out,
    +                                             const MCSubtargetInfo &STI) {
    +  const MCInstrDesc &Desc = InstInfo->get(Inst.getOpcode());
    +
    +  // The moffs form of mov encodes an absolute address in the instruction
    +  // instead of an addressing mode, so it is unsupported.
    +  if ((Desc.TSFlags & X86II::FormMask) == X86II::RawFrmMemOffs ||
    +      hasImplicitMemPointer(Inst.getOpcode()))
    +    return error(Inst, "unsupported memory access");
    +
    +  MCInst Sandboxed(Inst);
    +  sandboxMemAccess(Sandboxed);
    +  emitWithPrefixes(Sandboxed, Out, STI);
    +}
    +
    +namespace {
    +struct StringOpPointers {
    +  bool UsesDest;
    +  bool UsesSrc;
    +};
    +} // namespace
    +
    +static std::optional<StringOpPointers> getStringOpPointers(unsigned Opcode) {
    +  switch (Opcode) {
    +  case X86::STOSB:
    +  case X86::STOSW:
    +  case X86::STOSL:
    +  case X86::STOSQ:
    +  case X86::REP_STOSB_64:
    +  case X86::REP_STOSW_64:
    +  case X86::REP_STOSD_64:
    +  case X86::REP_STOSQ_64:
    +  case X86::SCASB:
    +  case X86::SCASW:
    +  case X86::SCASL:
    +  case X86::SCASQ:
    +    return StringOpPointers{true, false};
    +  case X86::MOVSB:
    +  case X86::MOVSW:
    +  case X86::MOVSL:
    +  case X86::MOVSQ:
    +  case X86::REP_MOVSB_64:
    +  case X86::REP_MOVSW_64:
    +  case X86::REP_MOVSD_64:
    +  case X86::REP_MOVSQ_64:
    +  case X86::CMPSB:
    +  case X86::CMPSW:
    +  case X86::CMPSL:
    +  case X86::CMPSQ:
    +    return StringOpPointers{true, true};
    +  case X86::LODSB:
    +  case X86::LODSW:
    +  case X86::LODSL:
    +  case X86::LODSQ:
    +    return StringOpPointers{false, true};
    +  default:
    +    return std::nullopt;
    +  }
    +}
    +
    +static void emitStringPtrFixup(MCRegister Reg, MCRegister Reg32,
    +                               MCStreamer &Out, const MCSubtargetInfo &STI) {
    +  Out.emitInstruction(MCInstBuilder(X86::MOV32rr).addReg(Reg32).addReg(Reg32),
    +                      STI);
    +
    +  Out.emitInstruction(MCInstBuilder(X86::LEA64r)
    +                          .addReg(Reg)
    +                          .addReg(LFIBaseReg)
    +                          .addImm(1)
    +                          .addReg(Reg)
    +                          .addImm(0)
    +                          .addReg(X86::NoRegister),
    +                      STI);
    +}
    +
    +// rep movsq
    +// ->
    +// .bundle_lock
    +// movl %edi, %edi
    +// leaq (%r14,%rdi), %rdi
    +// movl %esi, %esi
    +// leaq (%r14,%rsi), %rsi
    +// rep movsq
    +// .bundle_unlock
    +void X86::X86MCLFIRewriter::rewriteStringOperation(const MCInst &Inst,
    +                                                   MCStreamer &Out,
    +                                                   const MCSubtargetInfo &STI) {
    +  std::optional<StringOpPointers> Ptrs = getStringOpPointers(Inst.getOpcode());
    +  assert(Ptrs && "expected a string instruction");
    +
    +  // The guards below sandbox the full 64-bit %rdi and %rsi, so the access must
    +  // use them with a 64-bit address size and no %fs segment override.
    +  for (const MCOperand &Op : Inst) {
    +    if (!Op.isReg())
    +      continue;
    +    if (Op.getReg() == X86::EDI || Op.getReg() == X86::ESI)
    +      return error(Inst, "unsupported address size for string instruction");
    +    if (Op.getReg() == X86::FS)
    +      return error(Inst, "unsupported segment override for string instruction");
    +  }
    +
    +  Out.emitBundleLock(/*AlignToEnd=*/false, STI);
    +
    +  if (Ptrs->UsesDest)
    +    emitStringPtrFixup(X86::RDI, X86::EDI, Out, STI);
    +  if (Ptrs->UsesSrc)
    +    emitStringPtrFixup(X86::RSI, X86::ESI, Out, STI);
    +
    +  emitWithPrefixes(Inst, Out, STI);
    +
    +  Out.emitBundleUnlock(STI);
    +}
    +
    +// The register form of an instruction that modifies the stack and reads its
    +// source from memory, or 0 if there is none.
    +static unsigned memToRegOpcode(unsigned Opcode) {

    Consider returning a std::optional<unsigned> here instead.

    nickdesaulniers nickdesaulniers commented on code on Oct 20, 2026 18:10 UTC
    Code Review
    llvm/test/MC/X86/LFI/memory.s:1
    @@ -0,0 +1,156 @@
    +// RUN: llvm-mc -triple x86_64_lfi %s | FileCheck %s
    +
    +movq (%rax), %rdi
    +// CHECK: movq %gs:(%eax), %rdi
    +
    +movq %rcx, (%rax)
    +// CHECK: movq %rcx, %gs:(%eax)
    +
    +movq 8(%rax), %rdi
    +// CHECK: movq %gs:8(%eax), %rdi
    +
    +movq -8(%rax), %rdi
    +// CHECK: movq %gs:-8(%eax), %rdi
    +
    +movq (%rax,%rdi), %rcx
    +// CHECK: movq %gs:(%eax,%edi), %rcx
    +
    +movq 16(%rax,%rdi,4), %rcx
    +// CHECK: movq %gs:16(%eax,%edi,4), %rcx
    +
    +movq (,%rdi,8), %rcx
    +// CHECK: movq %gs:(,%edi,8), %rcx
    +
    +movl (%rax), %edi
    +// CHECK: movl %gs:(%eax), %edi
    +
    +movw (%rax), %di
    +// CHECK: movw %gs:(%eax), %di
    +
    +movb (%rax), %dil
    +// CHECK: movb %gs:(%eax), %dil
    +
    +movb (%rax), %ah
    +// CHECK: movb %gs:(%eax), %ah
    +
    +addq $1, (%rax)
    +// CHECK: addq $1, %gs:(%eax)
    +
    +incq (%rax)
    +// CHECK: incq %gs:(%eax)
    +
    +xchgq %rax, (%rcx)
    +// CHECK: xchgq %rax, %gs:(%ecx)
    +
    +lock incq (%rax)
    +// CHECK: lock {{.*}}incq %gs:(%eax)
    +
    +lock
    +addq $1, (%rax)
    +// CHECK:      lock
    +// CHECK-NEXT: addq $1, %gs:(%eax)
    +
    +movq (%rsp), %rax
    +// CHECK: movq (%rsp), %rax
    +
    +movq 8(%rsp), %rax
    +// CHECK: movq 8(%rsp), %rax
    +
    +movq %rax, -8(%rsp)
    +// CHECK: movq %rax, -8(%rsp)
    +
    +movq foo(%rip), %rax
    +// CHECK: movq foo(%rip), %rax
    +
    +movq %rax, foo(%rip)
    +// CHECK: movq %rax, foo(%rip)
    +
    +movq (%r14), %rax
    +// CHECK: movq (%r14), %rax
    +
    +movq 8(%r14), %rax
    +// CHECK: movq 8(%r14), %rax
    +
    +movq (%rsp,%rax), %rcx
    +// CHECK: movq %gs:(%esp,%eax), %rcx
    +
    +movq (%r14,%rax), %rcx
    +// CHECK: movq %gs:(%r14d,%eax), %rcx
    +
    +movq 4096, %rax
    +// CHECK: movq 4096(%r14), %rax
    +
    +vextractf64x2 $1, %zmm0, (%rax)
    +// CHECK: vextractf64x2 $1, %zmm0, %gs:(%eax)
    +
    +vextracti32x8 $1, %zmm0, 16(%rax,%rcx,4)
    +// CHECK: vextracti32x8 $1, %zmm0, %gs:16(%eax,%ecx,4)
    +
    +tileloaddrs 291(%rbp,%rax,4), %tmm3
    +// CHECK: tileloaddrs %gs:291(%ebp,%eax,4), %tmm3
    +
    +movq (%rax,%riz,1), %rbx
    +// CHECK: movq %gs:(%eax), %rbx
    +
    +movq (,%riz,1), %rbx
    +// CHECK: movq (%r14), %rbx
    +
    +movq 8(%rsp,%riz,8), %rbx
    +// CHECK: movq 8(%rsp), %rbx
    +
    +leaq (%rax), %rdi
    +// CHECK: leaq (%rax), %rdi
    +
    +leaq 8(%rax,%rcx,4), %rdi
    +// CHECK: leaq 8(%rax,%rcx,4), %rdi
    +
    +leal 4(%eax), %edx
    +// CHECK: leal 4(%eax), %edx
    +
    +nopw (%rax)
    +// CHECK: nopw (%rax)
    +
    +nopl (%rax,%rcx,4)
    +// CHECK: nopl (%rax,%rcx,4)
    +
    +movaps (%rdi), %xmm0
    +// CHECK: movaps %gs:(%edi), %xmm0
    +
    +movups %xmm1, 16(%rsi,%rdx,4)
    +// CHECK: movups %xmm1, %gs:16(%esi,%edx,4)
    +
    +flds (%rax)
    +// CHECK: flds %gs:(%eax)
    +
    +fstpl 8(%rsp)
    +// CHECK: fstpl 8(%rsp)
    +
    +vgatherdpd %xmm3, (%rax,%xmm2,8), %xmm0
    +// CHECK: vgatherdpd %xmm3, %gs:(%eax,%xmm2,8), %xmm0
    +
    +vgatherqps %xmm3, (%rdi,%xmm2,4), %xmm0
    +// CHECK: vgatherqps %xmm3, %gs:(%edi,%xmm2,4), %xmm0
    +
    +vpgatherdd (%rax,%ymm2,4), %ymm0 {%k1}
    +// CHECK: vpgatherdd %gs:(%eax,%ymm2,4), %ymm0 {%k1}
    +
    +vpscatterdd %ymm0, 16(%rax,%ymm2,4) {%k1}
    +// CHECK: vpscatterdd %ymm0, %gs:16(%eax,%ymm2,4) {%k1}
    +
    +vgatherpf0dps (%rax,%zmm2,4) {%k1}
    +// CHECK: vgatherpf0dps %gs:(%eax,%zmm2,4) {%k1}
    +
    +vgatherdpd %xmm3, (,%xmm2,8), %xmm0
    +// CHECK: vgatherdpd %xmm3, %gs:(%r14d,%xmm2,8), %xmm0
    +
    +vgatherdpd %xmm3, (%r14,%xmm2,8), %xmm0
    +// CHECK: vgatherdpd %xmm3, %gs:(%r14d,%xmm2,8), %xmm0
    +
    +pushq %rax
    +// CHECK: pushq %rax
    +
    +pushq (%rax)
    +// CHECK: pushq %gs:(%eax)
    +
    +popq (%rax)
    +// CHECK: popq %gs:(%eax)

    Please add tests for:

    movq %fs:0, %rsp
    addq %fs:0, %rsp
    

    (I suspect perhaps moving getWrittenStackReg(Inst) ahead of isFSAccess(Inst) in doRewriteInst handles all of these).

    nickdesaulniers nickdesaulniers commented on code on Oct 20, 2026 18:10 UTC
    Code Review
    llvm/test/MC/X86/LFI/memory-errors.s:1
    @@ -0,0 +1,146 @@
    +// RUN: not llvm-mc -triple x86_64_lfi -mattr=+clzero,+movdir64b,+enqcmd %s 2>&1 | FileCheck %s
    +
    +movq %gs:(%rax), %rbx
    +// CHECK: error: invalid use of reserved segment register %gs
    +
    +movq %gs:8, %rbx
    +// CHECK: error: invalid use of reserved segment register %gs
    +
    +movw %ax, %gs
    +// CHECK: error: illegal modification of reserved LFI register
    +
    +wrgsbase %rax
    +// CHECK: error: illegal modification of reserved segment base
    +
    +wrgsbasel %eax
    +// CHECK: error: illegal modification of reserved segment base
    +
    +wrfsbase %rax
    +// CHECK: error: illegal modification of reserved segment base
    +
    +wrfsbasel %eax
    +// CHECK: error: illegal modification of reserved segment base
    +
    +movabsq 0x123456789abcdef, %rax
    +// CHECK: error: unsupported memory access
    +
    +movabsb %al, 0x123456789abcdef
    +// CHECK: error: unsupported memory access
    +
    +xlatb
    +// CHECK: error: unsupported memory access
    +
    +maskmovdqu %xmm1, %xmm0
    +// CHECK: error: unsupported memory access
    +
    +xchgq %rax, %rsp
    +// CHECK: error: unsupported modification of the stack pointer
    +
    +shlq $1, %rsp
    +// CHECK: error: unsupported modification of the stack pointer
    +
    +movw %ax, %sp
    +// CHECK: error: unsupported modification of the stack pointer
    +
    +movl %eax, %esp
    +// CHECK: error: unsupported modification of the stack pointer
    +
    +addl $8, %esp
    +// CHECK: error: unsupported modification of the stack pointer
    +
    +xchgl %eax, %esp
    +// CHECK: error: unsupported modification of the stack pointer
    +
    +shll $1, %esp
    +// CHECK: error: unsupported modification of the stack pointer
    +
    +cmpxchgl %ecx, %esp
    +// CHECK: error: unsupported modification of the stack pointer
    +
    +gs movq (%rsp), %rax
    +// CHECK: error: unsupported instruction prefix
    +
    +fs movq (%rsp), %rax
    +// CHECK: error: unsupported instruction prefix
    +
    +addr32 movq (%rsp), %rax
    +// CHECK: error: unsupported instruction prefix
    +
    +rex64 movq %rdi, %rsp
    +// CHECK: error: unsupported instruction prefix
    +
    +data16 addq $8, %rsp
    +// CHECK: error: unsupported instruction prefix
    +
    +data16
    +leave
    +// CHECK: error: unsupported instruction prefix
    +
    +data16
    +retq $8
    +// CHECK: error: unsupported instruction prefix
    +
    +lock
    +jmpq *(%rdi)
    +// CHECK: error: unsupported instruction prefix
    +
    +lock jmpq *(%rdi)
    +// CHECK: error: unsupported lock prefix
    +
    +movl (%edi), %eax
    +// CHECK: error: unsupported 32-bit address size
    +
    +movq 8(%eax,%ecx,4), %rbx
    +// CHECK: error: unsupported 32-bit address size
    +
    +movq (%eax,%eiz), %rbx
    +// CHECK: error: unsupported 32-bit address size
    +
    +movq (,%eiz,1), %rbx
    +// CHECK: error: unsupported 32-bit address size
    +
    +movq (%esp), %rax
    +// CHECK: error: unsupported 32-bit address size
    +
    +movq foo(%eip), %rax
    +// CHECK: error: unsupported 32-bit address size
    +
    +jmpq *(%eax)
    +// CHECK: error: unsupported 32-bit address size
    +
    +vgatherdpd %xmm3, (%eax,%xmm2,8), %xmm0
    +// CHECK: error: unsupported 32-bit address size
    +
    +movsq (%esi), %es:(%edi)
    +// CHECK: error: unsupported address size for string instruction
    +
    +stosq %rax, %es:(%edi)
    +// CHECK: error: unsupported address size for string instruction
    +
    +movsq %fs:(%rsi), %es:(%rdi)
    +// CHECK: error: unsupported segment override for string instruction
    +
    +lodsq %fs:(%rsi), %rax
    +// CHECK: error: unsupported segment override for string instruction
    +
    +enter $16, $2
    +// CHECK: error: unsupported nesting level for enter
    +
    +clzero
    +// CHECK: error: unsupported memory access
    +
    +movdir64b (%rax), %rbx
    +// CHECK: error: unsupported memory access
    +
    +enqcmd (%rax), %rbx
    +// CHECK: error: unsupported memory access
    +
    +.code32
    +
    +lock
    +// CHECK: error: LFI only supports 64-bit mode
    +
    +.code64
    +
    +lock
    +// CHECK: error: unsupported instruction prefix

    Please add tests for:

    xchgq %rsp, %fs:0
    movl %fs:0, %esp
    btq %rax, (%rdi)
    btsq %rax, (%rdi)
    lock btsq %rax, (%rdi)
    

    nickdesaulniers nickdesaulniers commented on code on Oct 20, 2026 18:13 UTC
    Code Review
    llvm/lib/Target/X86/X86ISelLowering.cpp:1
    @@ -32855,6 +32797,11 @@ X86TargetLowering::shouldExpandLogicAtomicRMWInIR(
           return AtomicExpansionKind::None;
       }
     
    +  // Bit test accesses scaled by a register offset are not supported by LFI, so
    +  // we conservatively use the CmpXChg pattern instead.
    +  if (Subtarget.isLFI())
    +    return AtomicExpansionKind::CmpXChg;

    Missing unit test coverage for this. Probably should have a test under llvm/test/CodeGen/X86/ with a RUN line like RUN: llc < %s -mtriple=x86_64_lfi | FileCheck %s.

    nickdesaulniers nickdesaulniers commented on code on Oct 20, 2026 18:18 UTC
    Code Review
    llvm/lib/Target/X86/MCTargetDesc/X86MCLFIRewriter.cpp:1
    @@ -367,23 +427,469 @@ void X86::X86MCLFIRewriter::rewriteFSAccess(const MCInst &Inst, MCStreamer &Out,
       // movq %fs:(%rdi), %rax
       // ->
       // movq 16(%r15), %rax
    -  // movq (%rax,%rdi), %rax
    +  // movq %gs:(%eax,%edi), %rax
       MCInst Modified(Inst);
       Modified.getOperand(MemIdx + X86::AddrBaseReg).setReg(TPDest);
       if (HasBase && !HasIndex)
         Modified.getOperand(MemIdx + X86::AddrIndexReg).setReg(BaseReg);
       Modified.getOperand(MemIdx + X86::AddrSegmentReg).setReg(X86::NoRegister);
    -  Out.emitInstruction(Modified, STI);
    +  doRewriteInst(Modified, Out, STI);
    +}
    +
    +// Return true if Reg always contains an address within the sandbox.
    +static bool isSandboxBaseReg(MCRegister Reg) {
    +  return Reg == LFIBaseReg || Reg == X86::RSP || Reg == X86::RIP;
    +}
    +
    +// Return true if Inst reads or writes memory through a pointer register
    +// instead of an addressing mode, and so cannot be sandboxed by rewriting its
    +// operands.
    +static bool hasImplicitMemPointer(unsigned Opcode) {
    +  switch (Opcode) {
    +  // xlat loads from (%rbx,%al).
    +  case X86::XLAT:
    +  // maskmov stores to (%rdi).
    +  case X86::MASKMOVDQU:
    +  case X86::MASKMOVDQU64:
    +  case X86::VMASKMOVDQU:
    +  case X86::VMASKMOVDQU64:
    +  case X86::MMX_MASKMOVQ:
    +  case X86::MMX_MASKMOVQ64:
    +  // clzero zeroes the cache line at (%rax).
    +  case X86::CLZERO32r:
    +  case X86::CLZERO64r:
    +  // movdir64b and enqcmd store to the address in their register operand.
    +  case X86::MOVDIR64B32:
    +  case X86::MOVDIR64B64:
    +  case X86::MOVDIR64B32_EVEX:
    +  case X86::MOVDIR64B64_EVEX:
    +  case X86::ENQCMD32:
    +  case X86::ENQCMD64:
    +  case X86::ENQCMD32_EVEX:
    +  case X86::ENQCMD64_EVEX:
    +  case X86::ENQCMDS32:
    +  case X86::ENQCMDS64:
    +  case X86::ENQCMDS32_EVEX:
    +  case X86::ENQCMDS64_EVEX:
    +    return true;
    +  default:
    +    return false;
    +  }
    +}
    +
    +// Return true if Inst has a memory operand that is not dereferenced.
    +static bool ignoresMemOperand(unsigned Opcode) {
    +  switch (Opcode) {
    +  case X86::LEA16r:
    +  case X86::LEA32r:
    +  case X86::LEA64r:
    +  case X86::LEA64_32r:
    +  case X86::NOOPW:
    +  case X86::NOOPL:
    +  case X86::NOOPQ:
    +    return true;
    +  default:
    +    return false;
    +  }
    +}
    +
    +// Return true if the index register of the memory operand at MemIdx is a
    +// general-purpose register, and so can be truncated along with the base.
    +static bool hasGPRIndex(const MCInst &Inst, int MemIdx) {
    +  MCRegister Index = Inst.getOperand(MemIdx + X86::AddrIndexReg).getReg();
    +  return Index && getX86MCRegisterClass(X86::GR64RegClassID).contains(Index);
    +}
    +
    +// Return true if the memory operand at MemIdx uses a 32-bit address size,
    +// which is selected by a 32-bit base or index register.
    +static bool has32BitAddress(const MCInst &Inst, int MemIdx) {
    +  MCRegister Base = Inst.getOperand(MemIdx + X86::AddrBaseReg).getReg();
    +  MCRegister Index = Inst.getOperand(MemIdx + X86::AddrIndexReg).getReg();
    +  const MCRegisterClass &GR32 = getX86MCRegisterClass(X86::GR32RegClassID);
    +  return Base == X86::EIP || GR32.contains(Base) || Index == X86::EIZ ||
    +         GR32.contains(Index);
    +}
    +
    +// Rewrite the addressing mode of the memory operand at MemIdx so that the
    +// access it performs stays inside the sandbox.
    +//
    +// movq 8(%rax,%rcx,4), %rdi
    +// ->
    +// movq %gs:8(%eax,%ecx,4), %rdi
    +void X86::X86MCLFIRewriter::sandboxMemOperand(MCInst &Inst, int MemIdx) const {
    +  MCOperand &Base = Inst.getOperand(MemIdx + X86::AddrBaseReg);
    +  MCOperand &Scale = Inst.getOperand(MemIdx + X86::AddrScaleAmt);
    +  MCOperand &Index = Inst.getOperand(MemIdx + X86::AddrIndexReg);
    +  MCOperand &Segment = Inst.getOperand(MemIdx + X86::AddrSegmentReg);
    +
    +  // %riz only encodes the absence of an index register, so drop it and handle
    +  // the access as one without an index.
    +  if (Index.getReg() == X86::RIZ) {
    +    Index.setReg(X86::NoRegister);
    +    Scale.setImm(1);
    +  }
    +
    +  // A base register that always points into the sandbox needs no rewriting, as
    +  // long as there is no index register.
    +  if (isSandboxBaseReg(Base.getReg()) && !Index.getReg())
    +    return;
    +
    +  // An absolute address has no register to truncate, so make it relative to
    +  // the sandbox base instead.
    +  if (!Base.getReg() && !Index.getReg()) {
    +    Base.setReg(LFIBaseReg);
    +    return;
    +  }
    +
    +  // If there is no Base and the Index is not a GPR, then we use r14d (all
    +  // zeroes) as the base for the rewritten addressing mode.
    +  bool GPRIndex = hasGPRIndex(Inst, MemIdx);
    +
    +  Segment.setReg(LFIBaseSeg);
    +  if (Base.getReg())
    +    Base.setReg(getReg32(Base.getReg()));
    +  else if (!GPRIndex)
    +    Base.setReg(getReg32(LFIBaseReg));
    +  if (GPRIndex)
    +    Index.setReg(getReg32(Index.getReg()));
    +}
    +
    +void X86::X86MCLFIRewriter::sandboxMemAccess(MCInst &Inst) const {
    +  if (ignoresMemOperand(Inst.getOpcode()))
    +    return;
    +
    +  int MemIdx = X86II::getMemoryOperandIdx(InstInfo->get(Inst.getOpcode()));
    +  if (MemIdx >= 0)
    +    sandboxMemOperand(Inst, MemIdx);
    +}
    +
    +void X86::X86MCLFIRewriter::rewriteMemAccess(const MCInst &Inst,
    +                                             MCStreamer &Out,
    +                                             const MCSubtargetInfo &STI) {
    +  const MCInstrDesc &Desc = InstInfo->get(Inst.getOpcode());
    +
    +  // The moffs form of mov encodes an absolute address in the instruction
    +  // instead of an addressing mode, so it is unsupported.
    +  if ((Desc.TSFlags & X86II::FormMask) == X86II::RawFrmMemOffs ||
    +      hasImplicitMemPointer(Inst.getOpcode()))
    +    return error(Inst, "unsupported memory access");
    +
    +  MCInst Sandboxed(Inst);
    +  sandboxMemAccess(Sandboxed);
    +  emitWithPrefixes(Sandboxed, Out, STI);
    +}
    +
    +namespace {
    +struct StringOpPointers {
    +  bool UsesDest;
    +  bool UsesSrc;
    +};
    +} // namespace
    +
    +static std::optional<StringOpPointers> getStringOpPointers(unsigned Opcode) {
    +  switch (Opcode) {
    +  case X86::STOSB:
    +  case X86::STOSW:
    +  case X86::STOSL:
    +  case X86::STOSQ:
    +  case X86::REP_STOSB_64:
    +  case X86::REP_STOSW_64:
    +  case X86::REP_STOSD_64:
    +  case X86::REP_STOSQ_64:
    +  case X86::SCASB:
    +  case X86::SCASW:
    +  case X86::SCASL:
    +  case X86::SCASQ:
    +    return StringOpPointers{true, false};
    +  case X86::MOVSB:
    +  case X86::MOVSW:
    +  case X86::MOVSL:
    +  case X86::MOVSQ:
    +  case X86::REP_MOVSB_64:
    +  case X86::REP_MOVSW_64:
    +  case X86::REP_MOVSD_64:
    +  case X86::REP_MOVSQ_64:
    +  case X86::CMPSB:
    +  case X86::CMPSW:
    +  case X86::CMPSL:
    +  case X86::CMPSQ:
    +    return StringOpPointers{true, true};
    +  case X86::LODSB:
    +  case X86::LODSW:
    +  case X86::LODSL:
    +  case X86::LODSQ:
    +    return StringOpPointers{false, true};
    +  default:
    +    return std::nullopt;
    +  }
    +}
    +
    +static void emitStringPtrFixup(MCRegister Reg, MCRegister Reg32,
    +                               MCStreamer &Out, const MCSubtargetInfo &STI) {
    +  Out.emitInstruction(MCInstBuilder(X86::MOV32rr).addReg(Reg32).addReg(Reg32),
    +                      STI);
    +
    +  Out.emitInstruction(MCInstBuilder(X86::LEA64r)
    +                          .addReg(Reg)
    +                          .addReg(LFIBaseReg)
    +                          .addImm(1)
    +                          .addReg(Reg)
    +                          .addImm(0)
    +                          .addReg(X86::NoRegister),
    +                      STI);
    +}
    +
    +// rep movsq
    +// ->
    +// .bundle_lock
    +// movl %edi, %edi
    +// leaq (%r14,%rdi), %rdi
    +// movl %esi, %esi
    +// leaq (%r14,%rsi), %rsi
    +// rep movsq
    +// .bundle_unlock
    +void X86::X86MCLFIRewriter::rewriteStringOperation(const MCInst &Inst,
    +                                                   MCStreamer &Out,
    +                                                   const MCSubtargetInfo &STI) {
    +  std::optional<StringOpPointers> Ptrs = getStringOpPointers(Inst.getOpcode());
    +  assert(Ptrs && "expected a string instruction");
    +
    +  // The guards below sandbox the full 64-bit %rdi and %rsi, so the access must
    +  // use them with a 64-bit address size and no %fs segment override.
    +  for (const MCOperand &Op : Inst) {
    +    if (!Op.isReg())
    +      continue;
    +    if (Op.getReg() == X86::EDI || Op.getReg() == X86::ESI)
    +      return error(Inst, "unsupported address size for string instruction");
    +    if (Op.getReg() == X86::FS)
    +      return error(Inst, "unsupported segment override for string instruction");
    +  }
    +
    +  Out.emitBundleLock(/*AlignToEnd=*/false, STI);
    +
    +  if (Ptrs->UsesDest)
    +    emitStringPtrFixup(X86::RDI, X86::EDI, Out, STI);
    +  if (Ptrs->UsesSrc)
    +    emitStringPtrFixup(X86::RSI, X86::ESI, Out, STI);
    +
    +  emitWithPrefixes(Inst, Out, STI);
    +
    +  Out.emitBundleUnlock(STI);
    +}
    +
    +// The register form of an instruction that modifies the stack and reads its
    +// source from memory, or 0 if there is none.
    +static unsigned memToRegOpcode(unsigned Opcode) {
    +  switch (Opcode) {
    +  case X86::MOV64rm:
    +    return X86::MOV64rr;
    +  case X86::ADD64rm:
    +    return X86::ADD64rr;
    +  case X86::SUB64rm:
    +    return X86::SUB64rr;
    +  case X86::AND64rm:
    +    return X86::AND64rr;
    +  case X86::OR64rm:
    +    return X86::OR64rr;
    +  case X86::XOR64rm:
    +    return X86::XOR64rr;
    +  default:
    +    return 0;
    +  }
    +}
    +
    +// The 32-bit form of a 64-bit instruction, or 0 if the instruction has no
    +// 32-bit form that can be used to modify the stack pointer.
    +static unsigned demote64BitOpcode(unsigned Opcode) {
    +  switch (Opcode) {
    +  case X86::MOV64rr:
    +    return X86::MOV32rr;
    +  case X86::MOV64ri32:
    +    return X86::MOV32ri;
    +  case X86::LEA64r:
    +    return X86::LEA64_32r;
    +  case X86::ADD64rr:
    +    return X86::ADD32rr;
    +  case X86::ADD64ri8:
    +    return X86::ADD32ri8;
    +  case X86::ADD64ri32:
    +    return X86::ADD32ri;
    +  case X86::SUB64rr:
    +    return X86::SUB32rr;
    +  case X86::SUB64ri8:
    +    return X86::SUB32ri8;
    +  case X86::SUB64ri32:
    +    return X86::SUB32ri;
    +  case X86::AND64rr:
    +    return X86::AND32rr;
    +  case X86::AND64ri8:
    +    return X86::AND32ri8;
    +  case X86::AND64ri32:
    +    return X86::AND32ri;
    +  case X86::OR64rr:
    +    return X86::OR32rr;
    +  case X86::OR64ri8:
    +    return X86::OR32ri8;
    +  case X86::OR64ri32:
    +    return X86::OR32ri;
    +  case X86::XOR64rr:
    +    return X86::XOR32rr;
    +  case X86::XOR64ri8:
    +    return X86::XOR32ri8;
    +  case X86::XOR64ri32:
    +    return X86::XOR32ri;
    +  default:
    +    return 0;
    +  }
    +}
    +
    +MCRegister X86::X86MCLFIRewriter::getWrittenStackReg(const MCInst &Inst) const {
    +  const MCInstrDesc &Desc = InstInfo->get(Inst.getOpcode());
    +  for (unsigned I = 0, E = Desc.getNumDefs(); I < E; ++I) {
    +    const MCOperand &Op = Inst.getOperand(I);
    +    if (Op.isReg() && RegInfo->regsOverlap(Op.getReg(), X86::RSP))
    +      return Op.getReg();
    +  }
    +  return X86::NoRegister;
    +}
    +
    +// Emit leaq (%rsp,%r14), %rsp
    +static void emitStackFixup(MCStreamer &Out, const MCSubtargetInfo &STI) {
    +  Out.emitInstruction(MCInstBuilder(X86::LEA64r)
    +                          .addReg(X86::RSP)
    +                          .addReg(X86::RSP)
    +                          .addImm(1)
    +                          .addReg(LFIBaseReg)
    +                          .addImm(0)
    +                          .addReg(X86::NoRegister),
    +                      STI);
    +}
    +
    +// addq $8, %rsp
    +// ->
    +// .bundle_lock
    +// addl $8, %esp
    +// leaq (%rsp,%r14), %rsp
    +// .bundle_unlock
    +void X86::X86MCLFIRewriter::rewriteStackModification(
    +    MCRegister StackReg, const MCInst &Inst, MCStreamer &Out,
    +    const MCSubtargetInfo &STI) {
    +  if (StackReg != X86::RSP)
    +    return error(Inst, "unsupported modification of the stack pointer");
    +
    +  discardPrefixes();
    +
    +  // popq %rsp loads through the stack pointer that it overwrites, so it cannot
    +  // simply be demoted. Pop into the scratch register instead, and move the
    +  // result into %esp.
    +  if (Inst.getOpcode() == X86::POP64r) {
    +    Out.emitInstruction(MCInstBuilder(X86::POP64r).addReg(LFIScratchReg), STI);
    +
    +    Out.emitBundleLock(/*AlignToEnd=*/false, STI);
    +    Out.emitInstruction(
    +        MCInstBuilder(X86::MOV32rr).addReg(X86::ESP).addReg(X86::R11D), STI);
    +    emitStackFixup(Out, STI);
    +    Out.emitBundleUnlock(STI);
    +    return;
    +  }
    +
    +  // movq 8(%rdi), %rsp
    +  // ->
    +  // movq %gs:8(%edi), %r11
    +  // .bundle_lock
    +  // movl %r11d, %esp
    +  // leaq (%rsp,%r14), %rsp
    +  // .bundle_unlock
    +  int MemIdx = X86II::getMemoryOperandIdx(InstInfo->get(Inst.getOpcode()));
    +  if (MemIdx >= 0 && !ignoresMemOperand(Inst.getOpcode())) {
    +    unsigned RegOpcode = memToRegOpcode(Inst.getOpcode());
    +    if (!RegOpcode)
    +      return error(Inst, "unsupported modification of the stack pointer");
    +
    +    MCInstBuilder Load(X86::MOV64rm);
    +    Load.addReg(LFIScratchReg);
    +    for (unsigned I = 0; I < X86::AddrNumOperands; ++I)
    +      Load.addOperand(Inst.getOperand(MemIdx + I));
    +    Load.setLoc(Inst.getLoc());
    +    doRewriteInst(Load, Out, STI);
    +
    +    MCInstBuilder RegForm(RegOpcode);
    +    for (int I = 0; I < MemIdx; ++I)
    +      RegForm.addOperand(Inst.getOperand(I));
    +    RegForm.addReg(LFIScratchReg);
    +    RegForm.setLoc(Inst.getLoc());
    +    return doRewriteInst(RegForm, Out, STI);
    +  }
    +
    +  unsigned Opcode = demote64BitOpcode(Inst.getOpcode());
    +  if (!Opcode)
    +    return error(Inst, "unsupported modification of the stack pointer");
    +
    +  MCInst Modified(Inst);
    +  Modified.setOpcode(Opcode);
    +
    +  ArrayRef<MCOperandInfo> OpInfo = InstInfo->get(Opcode).operands();
    +  for (unsigned I = 0, E = std::min<unsigned>(OpInfo.size(),
    +                                              Modified.getNumOperands());
    +       I < E; ++I) {
    +    MCOperand &Op = Modified.getOperand(I);
    +    if (OpInfo[I].OperandType != MCOI::OPERAND_REGISTER || !Op.isReg())
    +      continue;
    +    if (getX86MCRegisterClass(X86::GR64RegClassID).contains(Op.getReg()))
    +      Op.setReg(RegInfo->getSubReg(Op.getReg(), X86::sub_32bit));
    +  }
    +
    +  sandboxMemAccess(Modified);
    +
    +  Out.emitBundleLock(/*AlignToEnd=*/false, STI);
    +  emitWithPrefixes(Modified, Out, STI);

    I think we've returned early for all relevant cases already, could this be simply:

      Out.emitBundleLock(/*AlignToEnd=*/false, STI);
      Out.emitInstruction(Modified, Out, STI);
    

    zyedidia zyedidia commented on code on Oct 23, 2026 00:58 UTC
    Code Review
    llvm/lib/Target/X86/X86ISelLowering.cpp:1
    @@ -32855,6 +32797,11 @@ X86TargetLowering::shouldExpandLogicAtomicRMWInIR(
           return AtomicExpansionKind::None;
       }
     
    +  // Bit test accesses scaled by a register offset are not supported by LFI, so
    +  // we conservatively use the CmpXChg pattern instead.
    +  if (Subtarget.isLFI())
    +    return AtomicExpansionKind::CmpXChg;

    I've added lfi-atomic-bit-test.ll with the new unit test coverage.

    nickdesaulniers nickdesaulniers commented on code on Oct 23, 2026 18:55 UTC
    Code Review
    llvm/test/MC/X86/LFI/memory-errors.s:1
    @@ -0,0 +1,164 @@
    +// RUN: not llvm-mc -triple x86_64_lfi -mattr=+clzero,+movdir64b,+enqcmd %s 2>&1 | FileCheck %s
    +
    +movq %gs:(%rax), %rbx
    +// CHECK: error: invalid use of reserved segment register %gs
    +
    +movq %gs:8, %rbx
    +// CHECK: error: invalid use of reserved segment register %gs
    +
    +movw %ax, %gs
    +// CHECK: error: illegal modification of reserved LFI register
    +
    +wrgsbase %rax
    +// CHECK: error: illegal modification of reserved segment base
    +
    +wrgsbasel %eax
    +// CHECK: error: illegal modification of reserved segment base
    +
    +wrfsbase %rax
    +// CHECK: error: illegal modification of reserved segment base
    +
    +wrfsbasel %eax
    +// CHECK: error: illegal modification of reserved segment base
    +
    +movabsq 0x123456789abcdef, %rax
    +// CHECK: error: unsupported memory access
    +
    +movabsb %al, 0x123456789abcdef
    +// CHECK: error: unsupported memory access
    +
    +xlatb
    +// CHECK: error: unsupported memory access
    +
    +maskmovdqu %xmm1, %xmm0
    +// CHECK: error: unsupported memory access
    +
    +xchgq %rax, %rsp
    +// CHECK: error: unsupported modification of the stack pointer
    +
    +shlq $1, %rsp
    +// CHECK: error: unsupported modification of the stack pointer
    +
    +movw %ax, %sp
    +// CHECK: error: unsupported modification of the stack pointer
    +
    +movl %eax, %esp
    +// CHECK: error: unsupported modification of the stack pointer
    +
    +addl $8, %esp
    +// CHECK: error: unsupported modification of the stack pointer
    +
    +xchgl %eax, %esp
    +// CHECK: error: unsupported modification of the stack pointer
    +
    +shll $1, %esp
    +// CHECK: error: unsupported modification of the stack pointer
    +
    +cmpxchgl %ecx, %esp
    +// CHECK: error: unsupported modification of the stack pointer
    +
    +xchgq %rsp, %fs:0
    +// CHECK: error: unsupported modification of the stack pointer
    +
    +movl %fs:0, %esp
    +// CHECK: error: unsupported modification of the stack pointer
    +
    +btq %rax, (%rdi)
    +// CHECK: error: unsupported bit test with a register bit offset
    +
    +btsq %rax, (%rdi)
    +// CHECK: error: unsupported bit test with a register bit offset
    +
    +lock btsq %rax, (%rdi)
    +// CHECK: error: unsupported bit test with a register bit offset
    +
    +btrl %eax, %fs:(%rdi)
    +// CHECK: error: unsupported bit test with a register bit offset
    +
    +gs movq (%rsp), %rax
    +// CHECK: error: unsupported instruction prefix
    +
    +fs movq (%rsp), %rax
    +// CHECK: error: unsupported instruction prefix
    +
    +addr32 movq (%rsp), %rax
    +// CHECK: error: unsupported instruction prefix
    +
    +rex64 movq %rdi, %rsp
    +// CHECK: error: unsupported instruction prefix
    +
    +data16 addq $8, %rsp
    +// CHECK: error: unsupported instruction prefix
    +
    +data16
    +leave
    +// CHECK: error: unsupported instruction prefix
    +
    +data16
    +retq $8
    +// CHECK: error: unsupported instruction prefix
    +
    +lock
    +jmpq *(%rdi)
    +// CHECK: error: unsupported instruction prefix
    +
    +lock jmpq *(%rdi)
    +// CHECK: error: unsupported lock prefix
    +
    +movl (%edi), %eax
    +// CHECK: error: unsupported 32-bit address size
    +
    +movq 8(%eax,%ecx,4), %rbx
    +// CHECK: error: unsupported 32-bit address size
    +
    +movq (%eax,%eiz), %rbx
    +// CHECK: error: unsupported 32-bit address size
    +
    +movq (,%eiz,1), %rbx
    +// CHECK: error: unsupported 32-bit address size
    +
    +movq (%esp), %rax
    +// CHECK: error: unsupported 32-bit address size
    +
    +movq foo(%eip), %rax
    +// CHECK: error: unsupported 32-bit address size
    +
    +jmpq *(%eax)
    +// CHECK: error: unsupported 32-bit address size
    +
    +vgatherdpd %xmm3, (%eax,%xmm2,8), %xmm0
    +// CHECK: error: unsupported 32-bit address size
    +
    +movsq (%esi), %es:(%edi)
    +// CHECK: error: unsupported address size for string instruction
    +
    +stosq %rax, %es:(%edi)
    +// CHECK: error: unsupported address size for string instruction
    +
    +movsq %fs:(%rsi), %es:(%rdi)
    +// CHECK: error: unsupported segment override for string instruction
    +
    +lodsq %fs:(%rsi), %rax
    +// CHECK: error: unsupported segment override for string instruction
    +
    +enter $16, $2
    +// CHECK: error: unsupported nesting level for enter
    +
    +clzero
    +// CHECK: error: unsupported memory access
    +
    +movdir64b (%rax), %rbx
    +// CHECK: error: unsupported memory access
    +
    +enqcmd (%rax), %rbx
    +// CHECK: error: unsupported memory access
    +
    +.code32
    +
    +lock
    +// CHECK: error: LFI only supports 64-bit mode
    +
    +.code64
    +
    +lock
    +// CHECK: error: unsupported instruction prefix

    Please add tests for:

    btq %rax, %fs:0
    btsq %rax, %fs:0
    movdir64b %fs:0, %rbx
    enqcmd %fs:0, %rbx
    

    phoebewang phoebewang commented on code on Oct 28, 2026 09:15 UTC
    Code Review
    llvm/docs/LFI.md:1
    @@ -715,15 +722,174 @@ are resolved at link time. Direct calls are placed at the end of a bundle.
     
     #### Memory accesses
     
    -**Note**: these rewrites have not been implemented.
    +Memory accesses are confined to the sandbox by rewriting the addressing mode.
    +The address is computed from 32-bit registers, so that it wraps within the
    +4GiB sandbox rather than escaping it, and a `%gs` segment override supplies the
    +sandbox base.
    +
    +An access based on a register that always holds an address inside the sandbox
    +is already safe, and is left alone. Those registers are `%rsp`, `%rip`, and
    +`%r14`.
    +
    +Every addressing mode is rewritten, except those that encode an address without
    +dereferencing it, such as `lea` and multi-byte nops.
    +
    +Only the addressing mode changes, so the rewrites are listed as addressing
    +modes rather than whole instructions.
    +
    +:::{list-table}
    +:header-rows: 1
    +
    +* - Original
    +  - Rewritten
    +* - ```gas
    +    N(%rX)
    +    ```
    +  - ```gas
    +    %gs:N(%eX)
    +    ```
    +* - ```gas
    +    N(%rX, %rY, S)
    +    ```
    +  - ```gas
    +    %gs:N(%eX, %eY, S)
    +    ```
    +* - ```gas
    +    N(, %rY, S)
    +    ```
    +  - ```gas
    +    %gs:N(, %eY, S)
    +    ```
    +* - ```gas
    +    N
    +    ```
    +  - ```gas
    +    N(%r14)
    +    ```
    +* - ```gas
    +    N({%rsp,%rip,%r14})

    Maybe %rsp/%rip/%r14?

    phoebewang phoebewang commented on code on Oct 28, 2026 09:20 UTC
    Code Review
    llvm/docs/LFI.md:1
    @@ -677,10 +684,10 @@ are resolved at link time. Direct calls are placed at the end of a bundle.
         jmpq *%rX
         ```
     * - ```gas
    -    jmpq *N(...)
    +    jmpq *N(%rX)
         ```
       - ```gas
    -    movq N(...), %r11
    +    movq %gs:N(%eX), %r11
         andl $-32, %r11d
         addq %r14, %r11

    Is the %gs replacing %r14? Should remove addq now? Otherwise, I don't see where the overhead save from.

    phoebewang phoebewang commented on code on Oct 28, 2026 09:35 UTC
    Code Review
    llvm/docs/LFI.md:1
    @@ -772,30 +942,30 @@ such instruction.
         ```
       - ```gas
         movq 16(%r15), %rD

    movl 16(%r15), %eD. The same for all the others.

    phoebewang phoebewang commented on code on Oct 28, 2026 09:57 UTC
    Code Review
    llvm/lib/Target/X86/MCTargetDesc/X86MCLFIRewriter.cpp:1
    @@ -403,10 +931,45 @@ void X86::X86MCLFIRewriter::doRewriteInst(const MCInst &Inst, MCStreamer &Out,
         return rewriteIndirectBranch(Inst, Out, STI);
       }
     
    +  for (const MCOperand &Op : Inst)
    +    if (Op.isReg() && Op.getReg() == LFIBaseSeg)
    +      return error(Inst, "invalid use of reserved segment register %gs");
    +
    +  if (MCRegister StackReg = getWrittenStackReg(Inst))
    +    return rewriteStackModification(StackReg, Inst, Out, STI);
    +
    +  // These accesses cannot be sandboxed by rewriting the addressing mode. The
    +  // moffs form of mov encodes an absolute address in the instruction instead
    +  // of an addressing mode.
    +  if ((InstInfo->get(Inst.getOpcode()).TSFlags & X86II::FormMask) ==
    +          X86II::RawFrmMemOffs ||
    +      hasImplicitMemPointer(Inst.getOpcode()))
    +    return error(Inst, "unsupported memory access");
    +
    +  if (isBitTestWithRegOffset(Inst.getOpcode()))
    +    return error(Inst, "unsupported bit test with a register bit offset");
    +
       if (isFSAccess(Inst))
         return rewriteFSAccess(Inst, Out, STI);
     
    -  Out.emitInstruction(Inst, STI);
    +  // The compiler never generates 32-bit addressing in 64-bit mode.

    LP64 mode.

    phoebewang phoebewang commented on code on Oct 28, 2026 10:00 UTC
    Code Review
    llvm/test/CodeGen/X86/lfi-atomic-bit-test.ll:1
    @@ -0,0 +1,42 @@
    +; NOTE: Assertions have been autogenerated by utils/update_llc_test_checks.py
    +; RUN: llc < %s -mtriple=x86_64_lfi | FileCheck %s
    +
    +; LFI cannot sandbox a bit test of memory with a register bit offset, so this
    +; uses a cmpxchg loop instead of lock btsq %reg, (mem).
    +define i64 @or_shl1(ptr %p, i64 %c) {
    +; CHECK-LABEL: or_shl1:
    +; CHECK:       # %bb.0:
    +; CHECK-NEXT:    movq %rsi, %rcx
    +; CHECK-NEXT:    movl $1, %edx
    +; CHECK-NEXT:    # kill: def $cl killed $cl killed $rcx
    +; CHECK-NEXT:    shlq %cl, %rdx
    +; CHECK-NEXT:    movq (%rdi), %rax

    Why no memory rewite instructions in the assemble?

    nickdesaulniers nickdesaulniers commented on code on Oct 29, 2026 19:04 UTC
    Code Review
    llvm/docs/LFI.md:1
    @@ -772,30 +942,30 @@ such instruction.
         ```
       - ```gas
         movq 16(%r15), %rD

    Sounds like a worthwhile optimization for X86MCLFIRewriter::emitTPLoad.

    zyedidia zyedidia commented on code on Nov 02, 2026 09:01 UTC
    Code Review
    llvm/docs/LFI.md:1
    @@ -715,15 +722,174 @@ are resolved at link time. Direct calls are placed at the end of a bundle.
     
     #### Memory accesses
     
    -**Note**: these rewrites have not been implemented.
    +Memory accesses are confined to the sandbox by rewriting the addressing mode.
    +The address is computed from 32-bit registers, so that it wraps within the
    +4GiB sandbox rather than escaping it, and a `%gs` segment override supplies the
    +sandbox base.
    +
    +An access based on a register that always holds an address inside the sandbox
    +is already safe, and is left alone. Those registers are `%rsp`, `%rip`, and
    +`%r14`.
    +
    +Every addressing mode is rewritten, except those that encode an address without
    +dereferencing it, such as `lea` and multi-byte nops.
    +
    +Only the addressing mode changes, so the rewrites are listed as addressing
    +modes rather than whole instructions.
    +
    +:::{list-table}
    +:header-rows: 1
    +
    +* - Original
    +  - Rewritten
    +* - ```gas
    +    N(%rX)
    +    ```
    +  - ```gas
    +    %gs:N(%eX)
    +    ```
    +* - ```gas
    +    N(%rX, %rY, S)
    +    ```
    +  - ```gas
    +    %gs:N(%eX, %eY, S)
    +    ```
    +* - ```gas
    +    N(, %rY, S)
    +    ```
    +  - ```gas
    +    %gs:N(, %eY, S)
    +    ```
    +* - ```gas
    +    N
    +    ```
    +  - ```gas
    +    N(%r14)
    +    ```
    +* - ```gas
    +    N({%rsp,%rip,%r14})

    I think the version in the document is consistent with the terminology section from the beginning.

    zyedidia zyedidia commented on code on Nov 02, 2026 09:01 UTC
    Code Review
    llvm/docs/LFI.md:1
    @@ -677,10 +684,10 @@ are resolved at link time. Direct calls are placed at the end of a bundle.
         jmpq *%rX
         ```
     * - ```gas
    -    jmpq *N(...)
    +    jmpq *N(%rX)
         ```
       - ```gas
    -    movq N(...), %r11
    +    movq %gs:N(%eX), %r11
         andl $-32, %r11d
         addq %r14, %r11

    This case is a jump to a target address that must be loaded from memory. The %gs covers the sandboxing of the memory load into %r11, but since segment registers don't apply to jump instructions, we still need to use %r14 to mask the target of the jump once it has been loaded into a register.

    zyedidia zyedidia commented on code on Nov 02, 2026 09:01 UTC
    Code Review
    llvm/docs/LFI.md:1
    @@ -772,30 +942,30 @@ such instruction.
         ```
       - ```gas
         movq 16(%r15), %rD

    I think this should stay as the 64-bit version since LFI pointers are still 64-bit despite being masked to 32-bit offsets at the load/store time. For stores-only or jumps-only modes (MPK integration), we need it to be possible to directly access pointers without masks, so they need to be 64-bit. The two forms should also be the same performance so we aren't losing anything by keeping it 64-bit.

    zyedidia zyedidia commented on code on Nov 02, 2026 09:01 UTC
    Code Review
    llvm/test/CodeGen/X86/lfi-atomic-bit-test.ll:1
    @@ -0,0 +1,42 @@
    +; NOTE: Assertions have been autogenerated by utils/update_llc_test_checks.py
    +; RUN: llc < %s -mtriple=x86_64_lfi | FileCheck %s
    +
    +; LFI cannot sandbox a bit test of memory with a register bit offset, so this
    +; uses a cmpxchg loop instead of lock btsq %reg, (mem).
    +define i64 @or_shl1(ptr %p, i64 %c) {
    +; CHECK-LABEL: or_shl1:
    +; CHECK:       # %bb.0:
    +; CHECK-NEXT:    movq %rsi, %rcx
    +; CHECK-NEXT:    movl $1, %edx
    +; CHECK-NEXT:    # kill: def $cl killed $cl killed $rcx
    +; CHECK-NEXT:    shlq %cl, %rdx
    +; CHECK-NEXT:    movq (%rdi), %rax

    The rewrite happens in the MC layer when the code is assembled, and llc's textual output is deliberately left unrewritten so it can be assembled later. This test only checks the ISel choice, so plain assembly is sufficient. We could send it through emit objects to apply the rewrites, like lfi-rep-string.ll does, but I don't think that's necessary for this case.

    nickdesaulniers nickdesaulniers commented on code on Nov 03, 2026 18:28 UTC
    Code Review
    llvm/docs/LFI.md:1
    @@ -772,30 +942,30 @@ such instruction.
         ```
       - ```gas
         movq 16(%r15), %rD

    ah, I assumed the 32b mov (which implicitly zeros the upper 32b) would have been a shorter encoding. Turns out, no! https://godbolt.org/z/5E3T7Wz9z

    nickdesaulniers nickdesaulniers approved these changes on Nov 03, 2026 18:28 UTC
    Approved Reviewer

    Approved these changes.

    phoebewang phoebewang approved these changes on Nov 08, 2026 12:45 UTC
    Approved Reviewer

    LGTM.

    Assignees
    zyedidia zyedidia
    Labels
    risk: low confidence: 84% reviewed
    Vouch Risk Breakdown
    AI-powered review risk analysis
    Change Risk
    Change Risk · Model 1 (XGBoost)
    Predicted defect probability (0.00–1.00) based on diff churn, modified sensitive files, and author risk history.
    Score: 59.1% (MEDIUM) · Higher = larger blast radius
    59.1%
    Review Confidence
    Review Confidence · Models 2 & 3
    Scrutiny score (0.00–1.00) combining DistilBERT semantic review depth with reviewer familiarity and session dwell time.
    Score: 84% · Lower = rushed or shallow review
    84%
    Residual Risk
    Residual Risk · Core Equation
    Residual = Change × (1 − Confidence)
    Unmitigated risk surviving review. ≥ 0.65 triggers an automated re-queue to protect production.
    Score: 9.4% · Safe to merge
    9.4%