codegen.cpp 2.1 KB

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