codegen.cpp 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. // Part of the Carbon Language project, under the Apache License v2.0 with LLVM
  2. // Exceptions. See /LICENSE for license information.
  3. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  4. #include "toolchain/codegen/codegen.h"
  5. #include <memory>
  6. #include "llvm/IR/LegacyPassManager.h"
  7. #include "llvm/MC/TargetRegistry.h"
  8. #include "llvm/Target/TargetOptions.h"
  9. #include "llvm/TargetParser/Host.h"
  10. namespace Carbon {
  11. auto CodeGen::Make(llvm::Module& module, llvm::StringRef target_triple,
  12. llvm::raw_pwrite_stream& errors) -> std::optional<CodeGen> {
  13. std::string error;
  14. const llvm::Target* target =
  15. llvm::TargetRegistry::lookupTarget(target_triple, error);
  16. if (!target) {
  17. errors << "error: invalid target: " << error << "\n";
  18. return {};
  19. }
  20. module.setTargetTriple(target_triple);
  21. constexpr llvm::StringLiteral CPU = "generic";
  22. constexpr llvm::StringLiteral Features = "";
  23. llvm::TargetOptions target_opts;
  24. CodeGen codegen(module, errors);
  25. codegen.target_machine_.reset(target->createTargetMachine(
  26. target_triple, CPU, Features, target_opts, llvm::Reloc::PIC_));
  27. return codegen;
  28. }
  29. auto CodeGen::EmitAssembly(llvm::raw_pwrite_stream& out) -> bool {
  30. return EmitCode(out, llvm::CodeGenFileType::AssemblyFile);
  31. }
  32. auto CodeGen::EmitObject(llvm::raw_pwrite_stream& out) -> bool {
  33. return EmitCode(out, llvm::CodeGenFileType::ObjectFile);
  34. }
  35. auto CodeGen::EmitCode(llvm::raw_pwrite_stream& out,
  36. llvm::CodeGenFileType file_type) -> bool {
  37. module_.setDataLayout(target_machine_->createDataLayout());
  38. // Using the legacy PM to generate the assembly since the new PM
  39. // does not work with this yet.
  40. // TODO: Make the new PM work with the codegen pipeline.
  41. llvm::legacy::PassManager pass;
  42. // Note that this returns true on an error.
  43. if (target_machine_->addPassesToEmitFile(pass, out, nullptr, file_type)) {
  44. errors_ << "error: unable to emit to this file\n";
  45. return false;
  46. }
  47. pass.run(module_);
  48. return true;
  49. }
  50. } // namespace Carbon