codegen.cpp 2.3 KB

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