4
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

GCC __attribute__((hot))

Posted at

GCCはFunction Attributeとして __attribute__((hot)) という属性を関数に付与することができます。

https://gcc.gnu.org/onlinedocs/gcc-4.3.5/gcc/Function-Attributes.html から引用すると、

hot
The hot attribute is used to inform the compiler that a function is a hot spot of the compiled program. The function is optimized more aggressively and on many target it is placed into special subsection of the text section so all hot functions appears close together improving locality.
When profile feedback is available, via -fprofile-use, hot functions are automatically detected and this attribute is ignored.
The hot attribute is not implemented in GCC versions earlier than 4.3.

この属性が付与された関数は積極的に最適化を行い多くの環境で特別なsubsectionに配置される、とあります。GCC 4.3から入ったようです。

これの何が嬉しいのかというと(上記説明にもありますが)、よく呼ばれる関数が一箇所に固まっているとCPUキャッシュのローカリティが高まり、L1/L2キャッシュのヒット率が向上することが期待できます。今年のLLVM Developer's MeetingでもCode Placementがパフォーマンスに与える影響についてIntelの人が話していました。(http://schd.ws/hosted_files/llvmdevelopersmeetingbay2016/d9/LLVM-Conference-US-2016-Code-Alignment.pdf)

special subsectionはどのようなものでしょう。LinuxのELFでは .text.hot というセクションに配置されるようです。確認してみましょう。

こういうプログラムを書きます。(特にhotが有用であるケースとかではないです、あくまで確認用なので。。)

__attribute__((hot))
int foo()
{
  return 1;
}

int main(void)
{
  int a = foo();
}

special subsectionはLoaderが解釈するものではありませんから、バイナリ表現では確認できません。そのため出力されるアセンブリをみてみます。

$ gcc -O3 -S hot.c
	.file	"hot.c"
	.section	.text.hot,"ax",@progbits
	.p2align 4,,15
	.globl	foo
	.type	foo, @function
foo:
.LFB0:
	.cfi_startproc
	movl	$1, %eax
	ret
	.cfi_endproc
.LFE0:
	.size	foo, .-foo
	.section	.text.startup,"ax",@progbits
	.p2align 4,,15
	.globl	main
	.type	main, @function
main:
.LFB1:
	.cfi_startproc
	xorl	%eax, %eax
	ret
	.cfi_endproc
.LFE1:
	.size	main, .-main
	.ident	"GCC: (Ubuntu 6.2.0-5ubuntu12) 6.2.0 20161005"
	.section	.note.GNU-stack,"",@progbits

.text.hot というsectionが確認できました。

4
4
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?