file_context.cpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319
  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/lower/file_context.h"
  5. #include "common/vlog.h"
  6. #include "llvm/ADT/STLExtras.h"
  7. #include "llvm/ADT/Sequence.h"
  8. #include "toolchain/lower/function_context.h"
  9. #include "toolchain/sem_ir/entry_point.h"
  10. #include "toolchain/sem_ir/file.h"
  11. #include "toolchain/sem_ir/inst.h"
  12. namespace Carbon::Lower {
  13. FileContext::FileContext(llvm::LLVMContext& llvm_context,
  14. llvm::StringRef module_name, const SemIR::File& sem_ir,
  15. llvm::raw_ostream* vlog_stream)
  16. : llvm_context_(&llvm_context),
  17. llvm_module_(std::make_unique<llvm::Module>(module_name, llvm_context)),
  18. sem_ir_(&sem_ir),
  19. vlog_stream_(vlog_stream) {
  20. CARBON_CHECK(!sem_ir.has_errors())
  21. << "Generating LLVM IR from invalid SemIR::File is unsupported.";
  22. }
  23. // TODO: Move this to lower.cpp.
  24. auto FileContext::Run() -> std::unique_ptr<llvm::Module> {
  25. CARBON_CHECK(llvm_module_) << "Run can only be called once.";
  26. // Lower all types that were required to be complete. Note that this may
  27. // leave some entries in `types_` null, if those types were mentioned but not
  28. // used.
  29. types_.resize(sem_ir_->types().size());
  30. for (auto type_id : sem_ir_->complete_types()) {
  31. types_[type_id.index] = BuildType(sem_ir_->types().Get(type_id).inst_id);
  32. }
  33. // Lower function declarations.
  34. functions_.resize_for_overwrite(sem_ir_->functions().size());
  35. for (auto i : llvm::seq(sem_ir_->functions().size())) {
  36. functions_[i] = BuildFunctionDecl(SemIR::FunctionId(i));
  37. }
  38. // TODO: Lower global variable declarations.
  39. // Lower function definitions.
  40. for (auto i : llvm::seq(sem_ir_->functions().size())) {
  41. BuildFunctionDefinition(SemIR::FunctionId(i));
  42. }
  43. // TODO: Lower global variable initializers.
  44. return std::move(llvm_module_);
  45. }
  46. auto FileContext::GetGlobal(SemIR::InstId inst_id) -> llvm::Value* {
  47. // All builtins are types, with the same empty lowered value.
  48. if (inst_id.index < SemIR::BuiltinKind::ValidCount) {
  49. return GetTypeAsValue();
  50. }
  51. auto target = sem_ir().insts().Get(inst_id);
  52. if (auto function_decl = target.TryAs<SemIR::FunctionDecl>()) {
  53. return GetFunction(function_decl->function_id);
  54. }
  55. if (target.type_id() == SemIR::TypeId::TypeType) {
  56. return GetTypeAsValue();
  57. }
  58. CARBON_FATAL() << "Missing value: " << inst_id << " " << target;
  59. }
  60. // Returns the parameter for the given instruction from a function parameter
  61. // list.
  62. static auto GetAsParam(const SemIR::File& sem_ir, SemIR::InstId pattern_id)
  63. -> std::pair<SemIR::InstId, SemIR::Param> {
  64. auto pattern = sem_ir.insts().Get(pattern_id);
  65. // Step over `addr`.
  66. if (auto addr = pattern.TryAs<SemIR::AddrPattern>()) {
  67. pattern_id = addr->inner_id;
  68. pattern = sem_ir.insts().Get(pattern_id);
  69. }
  70. return {pattern_id, pattern.As<SemIR::Param>()};
  71. }
  72. auto FileContext::BuildFunctionDecl(SemIR::FunctionId function_id)
  73. -> llvm::Function* {
  74. const auto& function = sem_ir().functions().Get(function_id);
  75. const bool has_return_slot = function.return_slot_id.is_valid();
  76. auto implicit_param_refs =
  77. sem_ir().inst_blocks().Get(function.implicit_param_refs_id);
  78. auto param_refs = sem_ir().inst_blocks().Get(function.param_refs_id);
  79. SemIR::InitRepr return_rep =
  80. function.return_type_id.is_valid()
  81. ? SemIR::GetInitRepr(sem_ir(), function.return_type_id)
  82. : SemIR::InitRepr{.kind = SemIR::InitRepr::None};
  83. CARBON_CHECK(return_rep.has_return_slot() == has_return_slot);
  84. llvm::SmallVector<llvm::Type*> param_types;
  85. // TODO: Consider either storing `param_inst_ids` somewhere so that we can
  86. // reuse it from `BuildFunctionDefinition` and when building calls, or factor
  87. // out a mechanism to compute the mapping between parameters and arguments on
  88. // demand.
  89. llvm::SmallVector<SemIR::InstId> param_inst_ids;
  90. auto max_llvm_params =
  91. has_return_slot + implicit_param_refs.size() + param_refs.size();
  92. param_types.reserve(max_llvm_params);
  93. param_inst_ids.reserve(max_llvm_params);
  94. if (has_return_slot) {
  95. param_types.push_back(GetType(function.return_type_id)->getPointerTo());
  96. param_inst_ids.push_back(function.return_slot_id);
  97. }
  98. for (auto param_ref_id :
  99. llvm::concat<const SemIR::InstId>(implicit_param_refs, param_refs)) {
  100. auto param_type_id = GetAsParam(sem_ir(), param_ref_id).second.type_id;
  101. switch (auto value_rep = SemIR::GetValueRepr(sem_ir(), param_type_id);
  102. value_rep.kind) {
  103. case SemIR::ValueRepr::Unknown:
  104. CARBON_FATAL()
  105. << "Incomplete parameter type lowering function declaration";
  106. case SemIR::ValueRepr::None:
  107. break;
  108. case SemIR::ValueRepr::Copy:
  109. case SemIR::ValueRepr::Custom:
  110. case SemIR::ValueRepr::Pointer:
  111. param_types.push_back(GetType(value_rep.type_id));
  112. param_inst_ids.push_back(param_ref_id);
  113. break;
  114. }
  115. }
  116. // If the initializing representation doesn't produce a value, set the return
  117. // type to void.
  118. llvm::Type* return_type = return_rep.kind == SemIR::InitRepr::ByCopy
  119. ? GetType(function.return_type_id)
  120. : llvm::Type::getVoidTy(llvm_context());
  121. std::string mangled_name;
  122. if (SemIR::IsEntryPoint(sem_ir(), function_id)) {
  123. // TODO: Add an implicit `return 0` if `Run` doesn't return `i32`.
  124. mangled_name = "main";
  125. } else if (auto name =
  126. sem_ir().names().GetAsStringIfIdentifier(function.name_id)) {
  127. // TODO: Decide on a name mangling scheme.
  128. mangled_name = *name;
  129. } else {
  130. CARBON_FATAL() << "Unexpected special name for function: "
  131. << function.name_id;
  132. }
  133. llvm::FunctionType* function_type =
  134. llvm::FunctionType::get(return_type, param_types, /*isVarArg=*/false);
  135. auto* llvm_function =
  136. llvm::Function::Create(function_type, llvm::Function::ExternalLinkage,
  137. mangled_name, llvm_module());
  138. // Set up parameters and the return slot.
  139. for (auto [inst_id, arg] :
  140. llvm::zip_equal(param_inst_ids, llvm_function->args())) {
  141. auto name_id = SemIR::NameId::Invalid;
  142. if (inst_id == function.return_slot_id) {
  143. name_id = SemIR::NameId::ReturnSlot;
  144. arg.addAttr(llvm::Attribute::getWithStructRetType(
  145. llvm_context(), GetType(function.return_type_id)));
  146. } else {
  147. name_id = GetAsParam(sem_ir(), inst_id).second.name_id;
  148. }
  149. arg.setName(sem_ir().names().GetIRBaseName(name_id));
  150. }
  151. return llvm_function;
  152. }
  153. auto FileContext::BuildFunctionDefinition(SemIR::FunctionId function_id)
  154. -> void {
  155. const auto& function = sem_ir().functions().Get(function_id);
  156. const auto& body_block_ids = function.body_block_ids;
  157. if (body_block_ids.empty()) {
  158. // Function is probably defined in another file; not an error.
  159. return;
  160. }
  161. llvm::Function* llvm_function = GetFunction(function_id);
  162. FunctionContext function_lowering(*this, llvm_function, vlog_stream_);
  163. const bool has_return_slot = function.return_slot_id.is_valid();
  164. // Add parameters to locals.
  165. // TODO: This duplicates the mapping between sem_ir instructions and LLVM
  166. // function parameters that was already computed in BuildFunctionDecl.
  167. // We should only do that once.
  168. auto implicit_param_refs =
  169. sem_ir().inst_blocks().Get(function.implicit_param_refs_id);
  170. auto param_refs = sem_ir().inst_blocks().Get(function.param_refs_id);
  171. int param_index = 0;
  172. if (has_return_slot) {
  173. function_lowering.SetLocal(function.return_slot_id,
  174. llvm_function->getArg(param_index));
  175. ++param_index;
  176. }
  177. for (auto param_ref_id :
  178. llvm::concat<const SemIR::InstId>(implicit_param_refs, param_refs)) {
  179. auto [param_id, param] = GetAsParam(sem_ir(), param_ref_id);
  180. auto param_type_id = param.type_id;
  181. if (SemIR::GetValueRepr(sem_ir(), param_type_id).kind ==
  182. SemIR::ValueRepr::None) {
  183. function_lowering.SetLocal(
  184. param_id, llvm::PoisonValue::get(GetType(param_type_id)));
  185. } else {
  186. function_lowering.SetLocal(param_id, llvm_function->getArg(param_index));
  187. ++param_index;
  188. }
  189. }
  190. // Lower all blocks.
  191. for (auto block_id : body_block_ids) {
  192. CARBON_VLOG() << "Lowering " << block_id << "\n";
  193. auto* llvm_block = function_lowering.GetBlock(block_id);
  194. // Keep the LLVM blocks in lexical order.
  195. llvm_block->moveBefore(llvm_function->end());
  196. function_lowering.builder().SetInsertPoint(llvm_block);
  197. function_lowering.LowerBlock(block_id);
  198. }
  199. // LLVM requires that the entry block has no predecessors.
  200. auto* entry_block = &llvm_function->getEntryBlock();
  201. if (entry_block->hasNPredecessorsOrMore(1)) {
  202. auto* new_entry_block = llvm::BasicBlock::Create(
  203. llvm_context(), "entry", llvm_function, entry_block);
  204. llvm::BranchInst::Create(entry_block, new_entry_block);
  205. }
  206. }
  207. auto FileContext::BuildType(SemIR::InstId inst_id) -> llvm::Type* {
  208. switch (inst_id.index) {
  209. case SemIR::BuiltinKind::FloatType.AsInt():
  210. // TODO: Handle different sizes.
  211. return llvm::Type::getDoubleTy(*llvm_context_);
  212. case SemIR::BuiltinKind::IntType.AsInt():
  213. // TODO: Handle different sizes.
  214. return llvm::Type::getInt32Ty(*llvm_context_);
  215. case SemIR::BuiltinKind::BoolType.AsInt():
  216. // TODO: We may want to have different representations for `bool` storage
  217. // (`i8`) versus for `bool` values (`i1`).
  218. return llvm::Type::getInt1Ty(*llvm_context_);
  219. case SemIR::BuiltinKind::FunctionType.AsInt():
  220. case SemIR::BuiltinKind::BoundMethodType.AsInt():
  221. case SemIR::BuiltinKind::NamespaceType.AsInt():
  222. // Return an empty struct as a placeholder.
  223. return llvm::StructType::get(*llvm_context_);
  224. default:
  225. // Handled below.
  226. break;
  227. }
  228. auto inst = sem_ir_->insts().Get(inst_id);
  229. switch (inst.kind()) {
  230. case SemIR::ArrayType::Kind: {
  231. auto array_type = inst.As<SemIR::ArrayType>();
  232. return llvm::ArrayType::get(
  233. GetType(array_type.element_type_id),
  234. sem_ir_->GetArrayBoundValue(array_type.bound_id));
  235. }
  236. case SemIR::ClassType::Kind: {
  237. auto object_repr_id = sem_ir_->classes()
  238. .Get(inst.As<SemIR::ClassType>().class_id)
  239. .object_repr_id;
  240. return GetType(object_repr_id);
  241. }
  242. case SemIR::ConstType::Kind:
  243. return GetType(inst.As<SemIR::ConstType>().inner_id);
  244. case SemIR::PointerType::Kind:
  245. return llvm::PointerType::get(*llvm_context_, /*AddressSpace=*/0);
  246. case SemIR::StructType::Kind: {
  247. auto fields =
  248. sem_ir_->inst_blocks().Get(inst.As<SemIR::StructType>().fields_id);
  249. llvm::SmallVector<llvm::Type*> subtypes;
  250. subtypes.reserve(fields.size());
  251. for (auto field_id : fields) {
  252. auto field = sem_ir_->insts().GetAs<SemIR::StructTypeField>(field_id);
  253. // TODO: Handle recursive types. The restriction for builtins prevents
  254. // recursion while still letting them cache.
  255. CARBON_CHECK(field.field_type_id.index < SemIR::BuiltinKind::ValidCount)
  256. << field.field_type_id;
  257. subtypes.push_back(GetType(field.field_type_id));
  258. }
  259. return llvm::StructType::get(*llvm_context_, subtypes);
  260. }
  261. case SemIR::TupleType::Kind: {
  262. // TODO: Investigate special-casing handling of empty tuples so that they
  263. // can be collectively replaced with LLVM's void, particularly around
  264. // function returns. LLVM doesn't allow declaring variables with a void
  265. // type, so that may require significant special casing.
  266. auto elements =
  267. sem_ir_->type_blocks().Get(inst.As<SemIR::TupleType>().elements_id);
  268. llvm::SmallVector<llvm::Type*> subtypes;
  269. subtypes.reserve(elements.size());
  270. for (auto element_id : elements) {
  271. subtypes.push_back(GetType(element_id));
  272. }
  273. return llvm::StructType::get(*llvm_context_, subtypes);
  274. }
  275. case SemIR::UnboundElementType::Kind: {
  276. // Return an empty struct as a placeholder.
  277. return llvm::StructType::get(*llvm_context_);
  278. }
  279. default: {
  280. CARBON_FATAL() << "Cannot use inst as type: " << inst_id << " " << inst;
  281. }
  282. }
  283. }
  284. } // namespace Carbon::Lower