You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何格式化GHC生成的LLVM输出以提升可读性?

解决GHC生成LLVM代码无格式的问题

方法1:使用LLVM自带工具格式化

GHC输出的LLVM IR是紧凑的无格式文本,LLVM官方工具可自动完成格式化:

  1. 将GHC的LLVM输出保存到文件:
    ghc -ddump-llvm Main.hs > raw.ll 2>&1
    
  2. 用llvm-as和llvm-dis转换并格式化:
    llvm-as raw.ll -o temp.bc && llvm-dis temp.bc -o formatted.ll
    
    生成的formatted.ll会包含带缩进、换行的可读性代码,效果和你手动格式化的片段一致。
  3. 也可通过管道一步完成,无需中间文件:
    ghc -ddump-llvm Main.hs 2>&1 | llvm-dis -o -
    

方法2:用clang-format格式化

clang-format支持LLVM IR的格式化,只需指定风格为LLVM:

ghc -ddump-llvm Main.hs 2>&1 | clang-format -style=LLVM > formatted.ll

方法3:GHC内置选项(限特定版本)

部分较新的GHC版本支持-fllvm-pretty选项,直接生成带格式的LLVM输出:

ghc -ddump-llvm -fllvm-pretty Main.hs

若你的GHC版本不支持该选项,优先使用前两种方法。

示例格式化效果

处理后会得到类似以下格式的LLVM代码:

internal global %Main_zdtcSubRegUnTup3_closure_struct<{
  i64 ptrtoint (i8* @ghczmprim_GHCziTypes_TyCon_con_info to i64),
  i64 add (i64 ptrtoint (%Main_zdtrModule_closure_struct* @Main_zdtrModule_closure$def to i64), i64 1),
  i64 add (i64 ptrtoint (%r24c_closure_struct* @r24c_closure$def to i64), i64 1),
  i64 ptrtoint (i8* @ghczmprim_GHCziTypes_krepzdzt_closure to i64),
  i64 3059269072134316734,
  i64 -1793863935995381901,
  i64 0,
  i64 0
}>

内容的提问来源于stack exchange,提问作者Daniil Iaitskov

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.20 05:50:50