Prédiction des branchements et exécution spéculative
Découvrez comment les CPU modernes prédisent les branchements et exécutent des instructions de manière spéculative pour masquer la latence, pourquoi les mauvaises prédictions coûtent des cycles et comment leurs effets secondaires ont mené aux attaques de type Spectre.
Prédiction des branchements et exécution spéculative est une leçon Assembly Language & x86 Low-Level Systems Programming gratuite sur CoddyKit. Ceci est la leçon 4 sur 4. Tu peux lire la leçon complète ci-dessous gratuitement — puis la pratiquer en direct dans le navigateur avec un éditeur de code intégré et un tuteur IA 24/7. Elle fait partie du parcours d'apprentissage Assembly Language & x86 Low-Level Systems Programming, et ta progression se synchronise sur le web et l'application CoddyKit. Le cours Assembly Language & x86 Low-Level Systems Programming comprend 4 leçons au total.
Certaines parties de cette leçon n'ont pas encore été traduites et s'affichent en anglais.
The Pipeline Problem
Modern CPUs are deeply pipelined, fetching and decoding many instructions ahead. But a conditional branch is a fork: the CPU does not yet know which path to fetch. Stalling would waste the whole pipeline.
Branch Prediction
To avoid stalls the CPU predicts which way a branch will go and keeps fetching. If correct, no time is lost. If wrong, the pipeline is flushed — a costly misprediction penalty of 15-20+ cycles.
How Predictors Learn
The Branch Target Buffer and history tables record past outcomes. A simple 2-bit saturating counter remembers whether a branch was recently taken, predicting that loops keep looping.
Speculative Execution
Beyond predicting, the CPU speculatively executes the predicted path before the condition resolves. If the guess holds, results are committed; if not, they are discarded as if they never ran — architecturally.
Writing Predictable Branches
You help the predictor by making branches consistent. A branch that is almost always taken predicts well; a random branch defeats prediction. Sorting data before a conditional loop can dramatically speed it up.
for (int i = 0; i < n; i++)
if (data[i] >= 128) // predictable only if data is sorted
sum += data[i];A Runnable Benchmark
This C program shows the dramatic effect of sorted vs unsorted data on a branch-heavy loop. Run it and compare timings.
#include <stdio.h>
#include <stdlib.h>
int main(void) {
int n = 32768;
int *d = malloc(n * sizeof(int));
for (int i = 0; i < n; i++) d[i] = rand() % 256;
long sum = 0;
for (int r = 0; r < 1000; r++)
for (int i = 0; i < n; i++)
if (d[i] >= 128) sum += d[i];
printf("sum=%ld\n", sum);
free(d);
return 0;
}Branchless Programming
You can sometimes eliminate a branch entirely with arithmetic or conditional-move instructions (cmov), so the CPU never needs to predict.
cmp eax, 128
cmovge ebx, ecx ; conditionally move, no branch to mispredictLikely/Unlikely Hints
Compilers expose hints like __builtin_expect (the source of likely()/unlikely() macros) so hot paths fall through and cold paths jump away, improving instruction-cache layout.
if (__builtin_expect(error, 0)) {
handle_error(); // marked cold/unlikely
}The Security Side Effect
Speculative results are discarded architecturally — but they leave traces in the cache. Speculatively loaded data warms cache lines, and that timing difference can be measured. This is the basis of side-channel leaks.
Spectre in a Nutshell
Spectre tricks the predictor into speculatively reading memory it should not, then leaks the value through a cache timing side channel. The reads never commit, so they bypass normal bounds checks during the speculation window.
Mitigations
Defenses include serializing instructions (lfence) to stop speculation past a bounds check, retpolines for indirect branches, and microcode updates. They trade some performance for safety.
cmp index, limit
jae out_of_range
lfence ; block speculation past the checkQuick Check
Test your understanding of speculation.
Recap
You learned how CPUs hide branch latency:
- Branch prediction guesses the path; mispredicts cost a pipeline flush
- Speculative execution runs the predicted path early
- Predictable branches, cmov, and likely/unlikely hints boost speed
- Speculation leaves cache side effects exploited by Spectre;
lfenceand retpolines mitigate it
Questions Fréquemment Posées
La leçon « Prédiction des branchements et exécution spéculative » est-elle gratuite ?
Oui — le texte complet de « Prédiction des branchements et exécution spéculative » est gratuit à lire ici sur le web. Pour la pratiquer de manière interactive (un éditeur de code intégré et un tuteur IA 24/7) et déverrouiller le reste du cours Assembly Language & x86 Low-Level Systems Programming, passe à CoddyKit PRO. Le cours Assembly Language & x86 Low-Level Systems Programming comprend 4 leçons au total.
Qu'est-ce que j'apprendrai dans « Prédiction des branchements et exécution spéculative » ?
Découvrez comment les CPU modernes prédisent les branchements et exécutent des instructions de manière spéculative pour masquer la latence, pourquoi les mauvaises prédictions coûtent des cycles et co… Tu pratiques Assembly Language & x86 Low-Level Systems Programming avec du code pratique que tu exécutes directement dans le navigateur, et un tuteur IA 24/7 répond à tes questions au fur et à mesure que tu avances dans la leçon.
Dois-je avoir de l'expérience pour commencer Assembly Language & x86 Low-Level Systems Programming ?
Aucune expérience préalable n'est requise. Assembly Language & x86 Low-Level Systems Programming sur CoddyKit est structuré pour les débutants jusqu'aux apprenants avancés, donc tu peux commencer ici ou depuis le début et avancer à ton rythme. Ceci est la leçon 4 sur 4.
Combien de temps prend la leçon « Prédiction des branchements et exécution spéculative » ?
La plupart des leçons CoddyKit prennent environ 5–10 minutes. Chacune est courte et interactive, tu progresses régulièrement et tu repiques exactement où tu t'es arrêté sur le web et l'app.
Peux-tu écrire et exécuter du code dans cette leçon Assembly Language & x86 Low-Level Systems Programming ?
Oui. Chaque leçon Assembly Language & x86 Low-Level Systems Programming inclut un éditeur de code intégré, tu écris et exécutes du vrai code directement dans ton navigateur et tu reçois des retours IA instantanés — aucune configuration locale requise.
Toutes les leçons de ce cours
- Cohérence du cache et performances
- Optimiser manuellement les sections critiques
- Dépassements de tampon et shellcode
- Prédiction des branchements et exécution spéculative