codegen.cpp 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  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. #include "toolchain/diagnostics/diagnostic_consumer.h"
  14. namespace Carbon {
  15. auto CodeGen::Make(llvm::Module* module, llvm::StringRef target_triple_str,
  16. Diagnostics::Consumer* consumer) -> std::optional<CodeGen> {
  17. std::string error;
  18. const llvm::Target* target =
  19. llvm::TargetRegistry::lookupTarget(target_triple_str, error);
  20. CARBON_CHECK(target, "Target should be validated before codegen: {0}", error);
  21. llvm::Triple target_triple(target_triple_str);
  22. module->setTargetTriple(target_triple);
  23. constexpr llvm::StringLiteral CPU = "generic";
  24. constexpr llvm::StringLiteral Features = "";
  25. llvm::TargetOptions target_opts;
  26. CodeGen codegen(module,
  27. consumer ? consumer : &Diagnostics::ConsoleConsumer());
  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. CARBON_DIAGNOSTIC(CodeGenUnableToEmit, Error,
  48. "unable to emit to this file");
  49. emitter_.Emit(module_->getName(), CodeGenUnableToEmit);
  50. return false;
  51. }
  52. pass.run(*module_);
  53. return true;
  54. }
  55. } // namespace Carbon