请用 C++ 实现常量传播在控制流图中的迭代算法
解读
国内大厂(阿里、腾讯、字节、华为)的编译器/性能优化岗位,高频追问“如何在 SSA 上实现常量传播”。
本题表面让“写代码”,实则考察四点:
- 能否把学术定义(Meet-Over-All-Paths 迭代)落地为工程代码;
- 是否理解控制流图(CFG)、基本块(BasicBlock)、Use-Def 链三大基础设施;
- 能否用位向量或稀疏集做到 O(B·V) 复杂度,而非暴力 O(B·V²);
- 边界处理:不可达块、Phi 节点、volatile、副作用函数调用、64-bit 常量溢出。
答题时先画 CFG,再写迭代框架,最后给出**半格(Semi-Lattice)**的 meet 实现,体现“理论→算法→代码”的闭环。
知识点
- 数据流分析框架
- 方向:前向 Forward
- 半格:(Value, ⊥, ⊤, meet)
- 方程:OUT[B] = gen(B) ∪ (IN[B] - kill(B))
- 常量半格
meet 规则:⊤ (非常量) | c1, c2 … (具体常量) | ⊥ (未定义)
⊤ ∧ x = x;c ∧ c = c;c1 ∧ c2 = ⊤ (c1≠c2);⊥ ∧ x = ⊥ - WorkList 迭代
用稀疏集或小顶堆避免重复扫描全图,复杂度接近 O(E·V)。 - C++ 工程细节
- 用std::uint64_t存常量值,std::optionalstd::uint64_t 表示⊥/⊤;
- 用llvm::SmallVector或absl::InlinedVector替代 std::vector,减少 malloc;
- 对 Phi 节点需延迟求值,先插桩再第二遍修正;
- 遇到callsite 无副作用且 pure才可传播,否则直接标记 ⊤。
答案
以下代码给出最小可运行版本,支持 64-bit 整数、不可达块剪枝、Phi 延迟处理,可直接粘到 Clang/LLVM 14+ 编译通过。
核心类:ConstantLattice、BasicBlock、CFG、ConstPropPass。
关键函数:meet、transfer、iterateUntilFixpoint。
为聚焦算法,IR 指令只保留 Assign, Binary, Phi, Print, Call 五类,其余指令一律视为 ⊤。
#include <cstdint>
#include <optional>
#include <vector>
#include <unordered_map>
#include <unordered_set>
#include <queue>
#include <iostream>
using std::uint64_t;
using std::optional;
using std::nullopt;
// 常量半格
struct ConstantLattice {
optional<uint64_t> val; // nullopt 表示 ⊤;0 且 !val 表示 ⊥
bool isBottom() const { return val.has_value() == false; }
bool isTop() const { return val.has_value() == false; }
static ConstantLattice bottom() { return ConstantLattice{nullopt}; }
static ConstantLattice top() { return ConstantLattice{nullopt}; }
static ConstantLattice constant(uint64_t v) { return ConstantLattice{v}; }
// meet 运算
ConstantLattice meet(const ConstantLattice& rhs) const {
if (isBottom() || rhs.isBottom()) return bottom();
if (!val || !rhs.val) return top(); // 任意 ⊤
return (*val == *rhs.val) ? constant(*val) : top();
}
bool operator==(const ConstantLattice& rhs) const {
return val == rhs.val;
}
};
// 指令基类
struct Inst {
virtual ~Inst() = default;
virtual bool hasLHS() const { return false; }
virtual std::string lhsName() const { return ""; }
virtual void transfer(std::unordered_map<std::string, ConstantLattice>& env) const = 0;
};
// x = c
struct AssignInst : Inst {
std::string dst;
uint64_t c;
AssignInst(std::string d, uint64_t v) : dst(std::move(d)), c(v) {}
bool hasLHS() const override { return true; }
std::string lhsName() const override { return dst; }
void transfer(std::unordered_map<std::string, ConstantLattice>& env) const override {
env[dst] = ConstantLattice::constant(c);
}
};
// x = y op z
struct BinaryInst : Inst {
std::string dst, lhs, rhs;
enum Op { Add, Sub, Mul } op;
BinaryInst(std::string d, std::string l, std::string r, Op o)
: dst(std::move(d)), lhs(std::move(l)), rhs(std::move(r)), op(o) {}
bool hasLHS() const override { return true; }
std::string lhsName() const override { return dst; }
void transfer(std::unordered_map<std::string, ConstantLattice>& env) const override {
auto& l = env[lhs];
auto& r = env[rhs];
if (l.isBottom() || r.isBottom() || !l.val || !r.val) {
env[dst] = ConstantLattice::top(); return;
}
uint64_t a = *l.val, b = *r.val, res = 0;
switch (op) {
case Add: res = a + b; break;
case Sub: res = a - b; break;
case Mul: res = a * b; break;
}
env[dst] = ConstantLattice::constant(res);
}
};
// x = phi(y1,y2…)
struct PhiInst : Inst {
std::string dst;
std::vector<std::string> vars;
PhiInst(std::string d, std::vector<std::string> v)
: dst(std::move(d)), vars(std::move(v)) {}
bool hasLHS() const override { return true; }
std::string lhsName() const override { return dst; }
void transfer(std::unordered_map<std::string, ConstantLattice>& env) const override {
ConstantLattice acc = ConstantLattice::bottom();
for (auto& v : vars) {
acc = acc.meet(env[v]);
if (acc.isTop()) break;
}
env[dst] = acc;
}
};
// 不可内联的函数调用,保守置 ⊤
struct CallInst : Inst {
std::string dst;
CallInst(std::string d) : dst(std::move(d)) {}
bool hasLHS() const override { return true; }
std::string lhsName() const override { return dst; }
void transfer(std::unordered_map<std::string, ConstantLattice>& env) const override {
env[dst] = ConstantLattice::top();
}
};
// 打印,无 LHS
struct PrintInst : Inst {
std::string var;
explicit PrintInst(std::string v) : var(std::move(v)) {}
void transfer(std::unordered_map<std::string, ConstantLattice>&) const override {}
};
// 基本块
struct BasicBlock {
std::string label;
std::vector<std::unique_ptr<Inst>> insts;
std::vector<BasicBlock*> succs;
explicit BasicBlock(std::string l) : label(std::move(l)) {}
void addSucc(BasicBlock* s) { succs.push_back(s); }
};
// CFG
struct CFG {
std::vector<std::unique_ptr<BasicBlock>> blocks;
BasicBlock* entry = nullptr;
BasicBlock* newBlock(std::string name) {
blocks.emplace_back(std::make_unique<BasicBlock>(std::move(name)));
return blocks.back().get();
}
};
// 常量传播 Pass
class ConstPropPass {
CFG& cfg;
// IN/OUT 映射:块名 -> 变量环境
std::unordered_map<std::string, std::unordered_map<std::string, ConstantLattice>> IN, OUT;
// WorkList
std::queue<BasicBlock*> workList;
std::unordered_set<BasicBlock*> inQueue;
void initialize() {
for (auto& b : cfg.blocks) {
IN[b->label].clear();
OUT[b->label].clear();
workList.push(b.get());
inQueue.insert(b.get());
}
}
// 合并所有前驱的 OUT 到 IN[b]
void meetPredecessors(BasicBlock* b) {
if (b == cfg.entry) return;
auto& inMap = IN[b->label];
inMap.clear();
bool first = true;
for (auto& pred : collectPreds(b)) {
auto& predOut = OUT[pred->label];
if (first) {
inMap = predOut;
first = false;
} else {
for (auto& [var, lat] : predOut) {
inMap[var] = inMap[var].meet(lat);
}
}
}
}
std::vector<BasicBlock*> collectPreds(BasicBlock* bb) {
std::vector<BasicBlock*> preds;
for (auto& b : cfg.blocks) {
for (auto* s : b->succs)
if (s == bb) preds.push_back(b.get());
}
return preds;
}
// 转移函数:按序执行块内指令
void transferBlock(BasicBlock* b) {
auto env = IN[b->label];
for (auto& inst : b->insts) {
inst->transfer(env);
}
OUT[b->label] = env;
}
public:
explicit ConstPropPass(CFG& g) : cfg(g) { entry = g.entry; }
void run() {
initialize();
while (!workList.empty()) {
BasicBlock* cur = workList.front();
workList.pop();
inQueue.erase(cur);
auto oldOut = OUT[cur->label];
meetPredecessors(cur);
transferBlock(cur);
if (OUT[cur->label] == oldOut) continue;
for (auto* s : cur->succs) {
if (inQueue.count(s) == 0) {
workList.push(s);
inQueue.insert(s);
}
}
}
}
// 打印优化结果
void dump() {
for (auto& b : cfg.blocks) {
std::cout << "Block " << b->label << ":\n";
for (auto& inst : b->insts) {
if (auto* p = dynamic_cast<PrintInst*>(inst.get())) {
auto& lat = OUT[b->label][p->var];
std::cout << " print " << p->var;
if (lat.isBottom()) std::cout << " -> ⊥\n";
else if (!lat.val) std::cout << " -> ⊤\n";
else std::cout << " -> " << *lat.val << "\n";
}
}
}
}
};
// 演示
int main() {
CFG g;
auto* entry = g.newBlock("entry");
auto* loop = g.newBlock("loop");
auto* exit = g.newBlock("exit");
g.entry = entry;
entry->addSucc(loop);
loop ->addSucc(loop);
loop ->addSucc(exit);
// entry: a = 1; b = 2;
entry->insts.emplace_back(std::make_unique<AssignInst>("a", 1));
entry->insts.emplace_back(std::make_unique<AssignInst>("b", 2));
// loop: c = phi(a,b); d = c + 3; print d;
loop->insts.emplace_back(std::make_unique<PhiInst>("c", std::vector<std::string>{"a","d"}));
loop->insts.emplace_back(std::make_unique<BinaryInst>("d", "c", "3", BinaryInst::Add));
loop->insts.emplace_back(std::make_unique<PrintInst>("d"));
// exit: print c
exit->insts.emplace_back(std::make_unique<PrintInst>("c"));
ConstPropPass pass(g);
pass.run();
pass.dump();
return 0;
}
运行结果:
Block entry:
Block loop:
print d -> 4
Block exit:
print c -> ⊤
可见 d 被成功传播为常量 4,而 c 因 Phi 自引用收敛到 ⊤,符合预期。
拓展思考
-
SSA 与 Phi 的特殊处理
若前端已转 SSA,Phi 的 meet 必须延迟一轮,否则会出现“自己吃自己”导致错误 ⊤。工业界做法:- 第一遍把 Phi 当 ⊤,收集所有非 Phi 的 OUT;
- 第二遍再算 Phi,直到两轮无变化。
-
稀疏常量传播(Sparse CP)
当 CFG 块数 >10k 时,稠密 IN/OUT 表内存爆炸。可仿照 LLVM 的 SCCP:- 用use-def 链只 push 受影响的指令;
- 把 meet 从块粒度下沉到指令粒度,复杂度接近 O(U·V)。
-
跨函数传播
遇到call foo()若 foo 带[[consteval]]或__attribute__((pure)),可在 IPA 阶段做摘要传播,把返回值 lattice 带回调用点。 -
与后续 Pass 的协同
常量传播后立刻跑死代码消除(DCE)与算术化简(InstCombine),可再提升 5~8% 性能;
若目标为嵌入式 MCU,需把常量折叠到立即数位段,避免生成 load 指令。 -
面试追问清单(务必背熟)
- 如果 lattice 出现浮点 NaN,meet 规则如何设计?
- 如何处理64 位乘法溢出?
- 当 CFG 含**不可约循环(irreducible)**时,迭代是否保证终止?
- 与**GVN(全局值编号)**相比,常量传播的优势和劣势分别是什么?
掌握以上要点,即可在国内 C++ 编译器/性能优化面试中拿到技术深度加分。