codegen.cpp 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  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 <optional>
  7. #include <string>
  8. #include "llvm/IR/LegacyPassManager.h"
  9. #include "llvm/MC/TargetRegistry.h"
  10. #include "llvm/Target/TargetOptions.h"
  11. #include "llvm/TargetParser/Host.h"
  12. namespace Carbon {
  13. auto CodeGen::Make(llvm::Module* module, llvm::StringRef target_triple_str,
  14. llvm::raw_pwrite_stream* errors) -> std::optional<CodeGen> {
  15. std::string error;
  16. const llvm::Target* target =
  17. llvm::TargetRegistry::lookupTarget(target_triple_str, error);
  18. if (!target) {
  19. *errors << "error: invalid target: " << error << "\n";
  20. return {};
  21. }
  22. llvm::Triple target_triple(target_triple_str);
  23. module->setTargetTriple(target_triple);
  24. constexpr llvm::StringLiteral CPU = "generic";
  25. constexpr llvm::StringLiteral Features = "";
  26. llvm::TargetOptions target_opts;
  27. CodeGen codegen(module, errors);
  28. codegen.target_machine_.reset(target->createTargetMachine(
  29. target_triple, CPU, Features, target_opts, llvm::Reloc::PIC_));
  30. return codegen;
  31. }
  32. auto CodeGen::EmitAssembly(llvm::raw_pwrite_stream& out) -> bool {
  33. return EmitCode(out, llvm::CodeGenFileType::AssemblyFile);
  34. }
  35. auto CodeGen::EmitObject(llvm::raw_pwrite_stream& out) -> bool {
  36. return EmitCode(out, llvm::CodeGenFileType::ObjectFile);
  37. }
  38. auto CodeGen::EmitCode(llvm::raw_pwrite_stream& out,
  39. llvm::CodeGenFileType file_type) -> bool {
  40. module_->setDataLayout(target_machine_->createDataLayout());
  41. // Using the legacy PM to generate the assembly since the new PM
  42. // does not work with this yet.
  43. // TODO: Make the new PM work with the codegen pipeline.
  44. llvm::legacy::PassManager pass;
  45. // Note that this returns true on an error.
  46. if (target_machine_->addPassesToEmitFile(pass, out, nullptr, file_type)) {
  47. *errors_ << "error: unable to emit to this file\n";
  48. return false;
  49. }
  50. pass.run(*module_);
  51. return true;
  52. }
  53. } // namespace Carbon