1 ===========================
2 LLVM Branch Weight Metadata
3 ===========================
11 Branch Weight Metadata represents branch weights as its likeliness to be
12 taken. Metadata is assigned to the ``TerminatorInst`` as a ``MDNode`` of the
13 ``MD_prof`` kind. The first operator is always a ``MDString`` node with the
14 string "branch_weights". Number of operators depends on the terminator type.
16 Branch weights might be fetch from the profiling file, or generated based on
17 `__builtin_expect`_ instruction.
19 All weights are represented as an unsigned 32-bit values, where higher value
20 indicates greater chance to be taken.
22 Supported Instructions
23 ======================
28 Metadata is only assigned to the conditional branches. There are two extra
29 operarands for the true and the false branch.
34 metadata !"branch_weights",
35 i32 <TRUE_BRANCH_WEIGHT>,
36 i32 <FALSE_BRANCH_WEIGHT>
42 Branch weights are assigned to every case (including the ``default`` case which
48 metadata !"branch_weights",
49 i32 <DEFAULT_BRANCH_WEIGHT>
50 [ , i32 <CASE_BRANCH_WEIGHT> ... ]
56 Branch weights are assigned to every destination.
61 metadata !"branch_weights",
62 i32 <LABEL_BRANCH_WEIGHT>
63 [ , i32 <LABEL_BRANCH_WEIGHT> ... ]
69 Other terminator instructions are not allowed to contain Branch Weight Metadata.
71 .. _\__builtin_expect:
73 Built-in ``expect`` Instructions
74 ================================
76 ``__builtin_expect(long exp, long c)`` instruction provides branch prediction
77 information. The return value is the value of ``exp``.
79 It is especially useful in conditional statements. Currently Clang supports two
80 conditional statements:
85 The ``exp`` parameter is the condition. The ``c`` parameter is the expected
86 comparison value. If it is equal to 1 (true), the condition is likely to be
87 true, in other case condition is likely to be false. For example:
91 if (__builtin_expect(x > 0, 1)) {
92 // This block is likely to be taken.
98 The ``exp`` parameter is the value. The ``c`` parameter is the expected
99 value. If the expected value doesn't show on the cases list, the ``default``
100 case is assumed to be likely taken.
104 switch (__builtin_expect(x, 5)) {
108 case 5: // This case is likely to be taken.
114 Branch Weight Metatada is not proof against CFG changes. If terminator operands'
115 are changed some action should be taken. In other case some misoptimizations may
116 occur due to incorrent branch prediction information.