Outils pour utilisateurs

Outils du site


lang:cpp:attribut

Les attributs ci-dessous sont standards et supportés par l'ensemble des compilateurs.

[[unlikely]] et [[likely]]

Il est possible d'indiquer au compilateur si une condition est généralement vraie ou fausse. Cela fonctionne sur if et case.

cpp/attribute/un-likely1.cpp
int s(int i);
int iff(int i);
 
int s(int i)
{
  switch (i)
  {
    case 1:
      return 1;
 
      [[likely]] case 2 : return 2;
 
      [[unlikely]] default : return 3;
  }
}
 
int iff(int i)
{
  int retval;
  if (i == 1)
  {
    retval = 1;
  }
  else if (i == 2)
    [[likely]] { retval = 2; }
  else
    [[unlikely]] { retval = 3; }
  return retval;
}
 
int main(int argc, char* /* argv */[]) { return s(argc) + iff(argc); }
Avec attributsSans attribut
cpp/attribute/unlikely1.cpp.asm
Disassembly of section .text:
 
0000000000000000 <s(int)>:
   0:	endbr64 
   4:	mov    eax,edi
   6:	cmp    edi,0x1
   9:	je     10 <s(int)+0x10>
   b:	cmp    edi,0x2
   e:	jne    11 <s(int)+0x11>
  10:	ret    
  11:	mov    eax,0x3
  16:	ret    
  17:	nop    WORD PTR [rax+rax*1+0x0]
 
0000000000000020 <iff(int)>:
  20:	endbr64 
  24:	mov    eax,edi
  26:	cmp    edi,0x1
  29:	je     36 <iff(int)+0x16>
  2b:	cmp    edi,0x2
  2e:	mov    edx,0x3
  33:	cmovne eax,edx
  36:	ret    
 
Disassembly of section .text.startup:
 
0000000000000000 <main>:
   0:	endbr64 
   4:	cmp    edi,0x1
   7:	je     16 <main+0x16>
   9:	cmp    edi,0x2
   c:	jne    1d <main+0x1d>
   e:	mov    eax,0x2
  13:	add    eax,edi
  15:	ret    
  16:	mov    eax,0x1
  1b:	jmp    13 <main+0x13>
  1d:	mov    eax,0x3
  22:	mov    edi,0x3
  27:	jmp    13 <main+0x13>
cpp/attribute/unlikely2.cpp.asm
Disassembly of section .text:
 
0000000000000000 <s(int)>:
   0:	endbr64 
   4:	mov    eax,edi
   6:	cmp    edi,0x1
   9:	je     16 <s(int)+0x16>
   b:	cmp    edi,0x2
   e:	mov    edx,0x3
  13:	cmovne eax,edx
  16:	ret    
  17:	nop    WORD PTR [rax+rax*1+0x0]
 
0000000000000020 <iff(int)>:
  20:	endbr64 
  24:	mov    eax,edi
  26:	cmp    edi,0x1
  29:	je     36 <iff(int)+0x16>
  2b:	cmp    edi,0x2
  2e:	mov    edx,0x3
  33:	cmovne eax,edx
  36:	ret    
 
Disassembly of section .text.startup:
 
0000000000000000 <main>:
   0:	endbr64 
   4:	mov    eax,0x1
   9:	cmp    edi,0x1
   c:	je     22 <main+0x22>
   e:	mov    eax,0x2
  13:	cmp    edi,0x2
  16:	je     22 <main+0x22>
  18:	mov    eax,0x3
  1d:	mov    edi,0x3
  22:	add    eax,edi
  24:	ret    

On voit que le code est différent pour le switch/case mais pas pour le if/then/else.

lang/cpp/attribut.txt · Dernière modification : 2020/07/18 23:54 de root