https://gcc.gnu.org/bugzilla/show_bug.cgi?id=127420

            Bug ID: 127420
           Summary: Emit UD2 after indirect jump
           Product: gcc
           Version: 17.0
            Status: UNCONFIRMED
          Severity: normal
          Priority: P3
         Component: target
          Assignee: unassigned at gcc dot gnu.org
          Reporter: hjl.tools at gmail dot com
  Target Milestone: ---
            Target: x86

The Intel optimization manual says:

| Assembly/Compiler Coding Rule 13. (M impact, L generality) When
| indirect branches are present, try to put the most likely target of
| an indirect branch immediately following the indirect
| branch. Alternatively, if indirect branches are common but they
| cannot be predicted by branch prediction hardware, then follow the
| indirect branch with a UD2 instruction, which will stop the
| processor from decoding down the fall-through path.

[hjl@gnu-tgl-3 tmp]$ cat x.c
extern void (*foo) (void);
extern void bar (void);

void
func1 (void)
{
  foo ();
}

void
func2 (void)
{
  bar ();
}
[hjl@gnu-tgl-3 tmp]$ gcc -O2 -S -fPIC -fno-plt x.c
[hjl@gnu-tgl-3 tmp]$ cat x.s
        .file   "x.c"
        .text
        .p2align 4
        .globl  func1
        .type   func1, @function
func1:
.LFB0:
        .cfi_startproc
        movq    foo@GOTPCREL(%rip), %rax
        jmp     *(%rax)
        .cfi_endproc
.LFE0:
        .size   func1, .-func1
        .p2align 4
        .globl  func2
        .type   func2, @function
func2:
.LFB1:
        .cfi_startproc
        jmp     *bar@GOTPCREL(%rip)
        .cfi_endproc
.LFE1:
        .size   func2, .-func2
        .ident  "GCC: (GNU) 16.2.1 20260819 (Red Hat 16.2.1-2)"
        .section        .note.GNU-stack,"",@progbits
[hjl@gnu-tgl-3 tmp]$ 

We should generate UD2 after indirect jump if not optimizing for space.

Reply via email to