aboutsummaryrefslogtreecommitdiff
path: root/src/main/java/org/shedlang/compiler/backends/llvm/LlvmCompiler.java
blob: 277b6874fcdda81e7e2d839b33d66fd5ef27ba77 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
package org.shedlang.compiler.backends.llvm;

import org.shedlang.compiler.backends.llvm.ir.LlvmIrSerializer;
import org.shedlang.compiler.backends.llvm.ir.ast.LlvmModule;
import org.shedlang.compiler.backends.paths.PartialTargetPath;

import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.List;

import static org.shedlang.compiler.util.processes.ProcessRunner.runInheritIo;

public class LlvmCompiler {
    private LlvmCompiler() {}

    public static Path compileLlvmModule(
        LlvmModule llvmModule,
        PartialTargetPath targetPath
    ) throws IOException, InterruptedException {
        var llvmModulePath = targetPath.withExtension(".ll");
        Files.createDirectories(llvmModulePath.getParent());
        var fileWriter = new FileWriter(llvmModulePath.toFile(), StandardCharsets.UTF_8);
        try (var writer = new BufferedWriter(fileWriter)) {
            LlvmIrSerializer.serializeModule(llvmModule, writer);
        }

        var objectPath = targetPath.withExtension(".o");
        runLlvmCompiler(llvmModulePath, objectPath);

        return objectPath;
    }

    private static void runLlvmCompiler(Path llvmModulePath, Path objectPath) throws IOException, InterruptedException {
        runInheritIo(List.of(
            "llc-23", llvmModulePath.toString(),
            "-filetype", "obj",
            "-relocation-model", "pic",
            "-o", objectPath.toString()
        ));
    }
}