3 ===========================
4 LLVM Branch Weight Metadata
5 ===========================
13 Branch Weight Metadata represents branch weights as its likeliness to be
14 taken. Metadata is assigned to the ``TerminatorInst`` as a ``MDNode`` of the
15 ``MD_prof`` kind. The first operator is always a ``MDString`` node with the
16 string "branch_weights". Number of operators depends on the terminator type.
18 Branch weights might be fetch from the profiling file, or generated based on
19 `__builtin_expect`_ instruction.
21 All weights are represented as an unsigned 32-bit values, where higher value
22 indicates greater chance to be taken.
24 Supported Instructions
25 ======================
30 Metadata is only assign to the conditional branches. There are two extra
31 operarands, for the true and the false branch.
36 metadata !"branch_weights",
37 i32 <TRUE_BRANCH_WEIGHT>,
38 i32 <FALSE_BRANCH_WEIGHT>
44 Branch weights are assign to every case (including ``default`` case which is
50 metadata !"branch_weights",
51 i32 <DEFAULT_BRANCH_WEIGHT>
52 [ , i32 <CASE_BRANCH_WEIGHT> ... ]
58 Branch weights are assign to every destination.
63 metadata !"branch_weights",
64 i32 <LABEL_BRANCH_WEIGHT>
65 [ , i32 <LABEL_BRANCH_WEIGHT> ... ]
71 Other terminator instructions are not allowed to contain Branch Weight Metadata.
73 .. _\__builtin_expect:
75 Built-in ``expect`` Instructions
76 ================================
78 ``__builtin_expect(long exp, long c)`` instruction provides branch prediction
79 information. The return value is the value of ``exp``.
81 It is especially useful in conditional statements. Currently Clang supports two
82 conditional statements:
87 The ``exp`` parameter is the condition. The ``c`` parameter is the expected
88 comparison value. If it is equal to 1 (true), the condition is likely to be
89 true, in other case condition is likely to be false. For example:
93 if (__builtin_expect(x > 0, 1)) {
94 // This block is likely to be taken.
100 The ``exp`` parameter is the value. The ``c`` parameter is the expected
101 value. If the expected value doesn't show on the cases list, the ``default``
102 case is assumed to be likely taken.
106 switch (__builtin_expect(x, 5)) {
110 case 5: // This case is likely to be taken.
116 Branch Weight Metatada is not proof against CFG changes. If terminator operands'
117 are changed some action should be taken. In other case some misoptimizations may
118 occur due to incorrent branch prediction information.