mirror of
https://github.com/carbon-language/carbon-lang.git
synced 2026-10-03 16:55:55 +01:00
This requires:
* Making `FunctionDecl` mutable since generating code
(`HandleTopLevelDecl()`) requires a mutable declaration and since we
manually add `used` attribute to force code generation.
* Passing the file system to `Lower` since it's needed by Clang code
generation.
* Creating an internal Clang LLVM module and link it against the Carbon
LLVM module.
Demo:
```c++
// hello_world.h
extern int puts;
inline void hello_world() {
((int (*)(const char*))&puts)("hello world");
}
```
```carbon
// main.carbon
library "Main";
import Cpp library "hello_world.h";
fn Run() -> i32 {
Cpp.hello_world();
return 0;
}
```
```shell
$ bazel-bin/toolchain/carbon compile main.carbon
$ bazel-bin/toolchain/carbon link main.o --output=demo
$ ./demo
hello world
```
Based on https://github.com/carbon-language/carbon-lang/pull/5406.
Part of #5405.
29 lines
1.1 KiB
C++
29 lines
1.1 KiB
C++
// Part of the Carbon Language project, under the Apache License v2.0 with LLVM
|
|
// Exceptions. See /LICENSE for license information.
|
|
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
|
|
|
|
#include "toolchain/lower/lower.h"
|
|
|
|
#include <memory>
|
|
#include <optional>
|
|
|
|
#include "toolchain/lower/file_context.h"
|
|
|
|
namespace Carbon::Lower {
|
|
|
|
auto LowerToLLVM(llvm::LLVMContext& llvm_context,
|
|
llvm::IntrusiveRefCntPtr<llvm::vfs::FileSystem> fs,
|
|
std::optional<llvm::ArrayRef<Parse::GetTreeAndSubtreesFn>>
|
|
tree_and_subtrees_getters_for_debug_info,
|
|
llvm::StringRef module_name, const SemIR::File& sem_ir,
|
|
clang::ASTUnit* cpp_ast, const SemIR::InstNamer* inst_namer,
|
|
llvm::raw_ostream* vlog_stream)
|
|
-> std::unique_ptr<llvm::Module> {
|
|
FileContext context(llvm_context, std::move(fs),
|
|
tree_and_subtrees_getters_for_debug_info, module_name,
|
|
sem_ir, cpp_ast, inst_namer, vlog_stream);
|
|
return context.Run();
|
|
}
|
|
|
|
} // namespace Carbon::Lower
|