Skill站外收录 @skilllib/skill-2117939930272415310
compiler-development
基于 LLVM 构建编译器与编程语言实现,涵盖词法分析、语法解析、AST 转换及中间代码生成。通过 IR 优化流水线与 JIT 执行支持自定义语言的高效运行,适用于领域专用语言与系统级语言开发。
软件开发 AI 技能
Skills.MD
# Compiler Development Skill
This skill provides comprehensive knowledge of building compilers and language implementations using the LLVM infrastructure.
## Compiler Architecture Overview
### Classic Three-Phase Design
```
Source Code → Frontend → Middle-End (Optimizer) → Backend → Machine Code
↓ ↓ ↓
AST/IR LLVM IR Passes Target Code
```
## Frontend Development
### Lexical Analysis
```cpp
// Token types for a simple language
enum class TokenKind {
Identifier,
Number,
String,
Keyword,
Operator,
Punctuation,
EndOfFile
};
struct Token {
TokenKind kind;
std::string value;
SourceLocation location;
};
```
### Parser Implementation
- Recursive Descent: Easy to implement, good error messages
- Operator Precedence Parsing: Efficient for expression parsing
- LALR/LR: Use tools like Bison for complex grammars
### AST Design
```cpp
class Expr {
public:
virtual ~Expr() = default;
virtual llvm::Value* codegen() = 0;
};
class BinaryExpr : public Expr {
std::unique_ptr<Expr> LHS, RHS;
char Op;
public:
llvm::Value* codegen() override {
llvm::Value* L = LHS->codegen();
llvm::Value* R = RHS->codegen();
switch (Op) {
case '+': return Builder.CreateFAdd(L, R, "addtmp");
case '-': return Builder.CreateFSub(L, R, "subtmp");
case '*': return Builder.CreateFMul(L, R, "multmp");
case '/': return Builder.CreateFDiv(L, R, "divtmp");
}
}
};
```
## LLVM IR Generation
### Module and Context Setup
```cpp
#include "llvm/IR/LLVMContext.h"
#include "llvm/IR/Module.h"
#include "llvm/IR/IRBuilder.h"
class CodeGen {
std::unique_ptr<llvm::LLVMContext> Context;
std::unique_ptr<llvm::Module> Module;
std::unique_ptr<llvm::IRBuilder<>> Builder;
public:
CodeGen() {
Context = std::make_unique<llvm::LLVMContext>();
Module = std::make_unique<llvm::Module>("my_module", *Context);
Builder = std::make_unique<llvm::IRBuilder<>>(*Context);
}
};
```
### Function Generation
```cpp
llvm::Function* createFunction(const std::string& name,
llvm::Type* returnType,
std::vector<llvm::Type*> params) {
llvm::FunctionType* FT = llvm::FunctionType::get(returnType, params, false);
llvm::Function* F = llvm::Function::Create(
FT, llvm::Function::ExternalLinkage, name, Module.get());
llvm::BasicBlock* BB = llvm::BasicBlock::Create(*Context, "entry", F);
Builder->SetInsertPoint(BB);
return F;
}
```
## JIT Compilation
### LLVM ORC JIT
```cpp
#include "llvm/ExecutionEngine/Orc/LLJIT.h"
auto JIT = llvm::orc::LLJITBuilder().create();
if (!JIT) {
handleError(JIT.takeError());
}
// Add module
(*JIT)->addIRModule(llvm::orc::ThreadSafeModule(
std::move(Module), std::move(Context)));
// Look up symbol and execute
auto Sym = (*JIT)->lookup("main");
auto* MainFn = (int(*)())Sym->getAddress();
int result = MainFn();
```
## Optimization Pass Pipeline
### New Pass Manager (Recommended)
```cpp
#include "llvm/Passes/PassBuilder.h"
void optimizeModule(llvm::Module& M) {
llvm::PassBuilder PB;
llvm::LoopAnalysisManager LAM;
llvm::FunctionAnalysisManager FAM;
llvm::CGSCCAnalysisManager CGAM;
llvm::ModuleAnalysisManager MAM;
PB.registerModuleAnalyses(MAM);
PB.registerCGSCCAnalyses(CGAM);
PB.registerFunctionAnalyses(FAM);
PB.registerLoopAnalyses(LAM);
PB.crossRegisterProxies(LAM, FAM, CGAM, MAM);
llvm::ModulePassManager MPM = PB.buildPerModuleDefaultPipeline(
llvm::OptimizationLevel::O2);
MPM.run(M, MAM);
}
```
### Custom Pass Implementation
```cpp
struct MyPass : public llvm::PassInfoMixin<MyPass> {
llvm::PreservedAnalyses run(llvm::Function& F,
llvm::FunctionAnalysisManager& FAM) {
for (auto& BB : F) {
for (auto& I : BB) {
// Transform instructions
}
}
return llvm::PreservedAnalyses::none();
}
};
```
## Language Implementation Patterns
### Memory-Safe Languages
- Use LLVM's memory sanitizer hooks
- Implement bounds checking with GEP introspection
- Reference counting or garbage collection integration
### Type Systems
- Implement type inference during AST construction
- Generate appropriate LLVM types (i32, float, struct, ptr)
- Handle generic types via monomorphization or boxing
### Error Handling
- Generate exception handling via LLVM's landingpad/invoke
- Implement Result/Option types as tagged unions
- Use LLVM's personality functions for unwinding
## Notable Language Implementations
### Systems Languages
- **Rust**: Complex borrow checker, trait system → LLVM
- **Zig**: Comptime evaluation, safety features
- **Carbon**: C++ interop, modern syntax
### Scripting Languages
- **Julia**: JIT-compiled scientific computing
- **Crystal**: Ruby-like syntax, static typing
- **Nim**: Python-like, multi-backend
### Domain-Specific
- **Solidity**: Ethereum smart contracts
- **MLIR**: Multi-level IR for ML/AI workloads
- **Halide**: Image processing DSL
## Development Workflow
1. **Start Simple**: Begin with Kaleidoscope tutorial
2. **Incremental Features**: Add one language feature at a time
3. **Test Extensively**: Unit tests for each compiler phase
4. **Use LLVM Tools**: opt, llc, llvm-dis for debugging IR
5. **Profile and Optimize**: Focus on common code patterns
## Resources
### Official Tutorials
- LLVM Kaleidoscope: Building a language from scratch
- Clang internals: Frontend implementation patterns
- Writing an LLVM Backend: Target code generation
### Community Projects
See DIY Compiler section in README.md for 100+ example implementations across different language paradigms.
评论 0
还没有评论,来抢沙发。
相关内容
同类或同场景的收录内容
building-with-kafka-strimzi
在 Kubernetes 上构建基于 Apache Kafka 的事件驱动系统,支持高可靠的消息传递、事务性处理与精确一次语义,结合 Strimzi 运营商实现集群自动化管理,利用 Schema Registry 保障事件模式演进,适用于微服务间解耦通信与实时数据流处理场景。
站外数据与分析
609 0.0
personal-tool-builder
专注于从个人真实痛点出发快速构建实用工具,涵盖命令行程序、本地优先应用和自动化脚本的开发与演进,强调先满足自身需求再逐步扩展,通过持续自用打磨功能,避免过度设计,确保工具简洁有效且长期可维护。
站外商业与营销
196 0.0
threejs-lighting
实现三维场景中的光照与阴影控制,支持多种光源类型及环境光照明,提供从基础布光到高级阴影优化的完整方案,适用于需要真实感渲染或性能平衡的可视化项目。
站外效率工具
442 0.0
aggregation-helper
提供数据聚合场景的自动化辅助能力,涵盖 SQL 查询编写、统计分析建模、可视化方案设计及商业智能配置,支持从需求理解到生产级代码生成的全流程指导。
站外效率工具数据与分析
217 0.0
举报「compiler-development」
举报信息仅审核团队可见,同一资产 24 小时内仅可举报一次