file_context.cpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307
  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. auto FileContext::BuildFunctionDecl(SemIR::FunctionId function_id)
  61. -> llvm::Function* {
  62. const auto& function = sem_ir().functions().Get(function_id);
  63. const bool has_return_slot = function.return_slot_id.is_valid();
  64. auto implicit_param_refs =
  65. sem_ir().inst_blocks().Get(function.implicit_param_refs_id);
  66. auto param_refs = sem_ir().inst_blocks().Get(function.param_refs_id);
  67. SemIR::InitRepr return_rep =
  68. function.return_type_id.is_valid()
  69. ? SemIR::GetInitRepr(sem_ir(), function.return_type_id)
  70. : SemIR::InitRepr{.kind = SemIR::InitRepr::None};
  71. CARBON_CHECK(return_rep.has_return_slot() == has_return_slot);
  72. llvm::SmallVector<llvm::Type*> param_types;
  73. // TODO: Consider either storing `param_inst_ids` somewhere so that we can
  74. // reuse it from `BuildFunctionDefinition` and when building calls, or factor
  75. // out a mechanism to compute the mapping between parameters and arguments on
  76. // demand.
  77. llvm::SmallVector<SemIR::InstId> param_inst_ids;
  78. auto max_llvm_params =
  79. has_return_slot + implicit_param_refs.size() + param_refs.size();
  80. param_types.reserve(max_llvm_params);
  81. param_inst_ids.reserve(max_llvm_params);
  82. if (has_return_slot) {
  83. param_types.push_back(GetType(function.return_type_id)->getPointerTo());
  84. param_inst_ids.push_back(function.return_slot_id);
  85. }
  86. for (auto param_ref_id :
  87. llvm::concat<const SemIR::InstId>(implicit_param_refs, param_refs)) {
  88. auto param_type_id = sem_ir().insts().Get(param_ref_id).type_id();
  89. switch (auto value_rep = SemIR::GetValueRepr(sem_ir(), param_type_id);
  90. value_rep.kind) {
  91. case SemIR::ValueRepr::Unknown:
  92. CARBON_FATAL()
  93. << "Incomplete parameter type lowering function declaration";
  94. case SemIR::ValueRepr::None:
  95. break;
  96. case SemIR::ValueRepr::Copy:
  97. case SemIR::ValueRepr::Custom:
  98. case SemIR::ValueRepr::Pointer:
  99. param_types.push_back(GetType(value_rep.type_id));
  100. param_inst_ids.push_back(param_ref_id);
  101. break;
  102. }
  103. }
  104. // If the initializing representation doesn't produce a value, set the return
  105. // type to void.
  106. llvm::Type* return_type = return_rep.kind == SemIR::InitRepr::ByCopy
  107. ? GetType(function.return_type_id)
  108. : llvm::Type::getVoidTy(llvm_context());
  109. std::string mangled_name;
  110. if (SemIR::IsEntryPoint(sem_ir(), function_id)) {
  111. // TODO: Add an implicit `return 0` if `Run` doesn't return `i32`.
  112. mangled_name = "main";
  113. } else if (auto name =
  114. sem_ir().names().GetAsStringIfIdentifier(function.name_id)) {
  115. // TODO: Decide on a name mangling scheme.
  116. mangled_name = *name;
  117. } else {
  118. CARBON_FATAL() << "Unexpected special name for function: "
  119. << function.name_id;
  120. }
  121. llvm::FunctionType* function_type =
  122. llvm::FunctionType::get(return_type, param_types, /*isVarArg=*/false);
  123. auto* llvm_function =
  124. llvm::Function::Create(function_type, llvm::Function::ExternalLinkage,
  125. mangled_name, llvm_module());
  126. // Set up parameters and the return slot.
  127. for (auto [inst_id, arg] :
  128. llvm::zip_equal(param_inst_ids, llvm_function->args())) {
  129. auto inst = sem_ir().insts().Get(inst_id);
  130. auto name_id = SemIR::NameId::Invalid;
  131. if (inst_id == function.return_slot_id) {
  132. name_id = SemIR::NameId::ReturnSlot;
  133. arg.addAttr(llvm::Attribute::getWithStructRetType(
  134. llvm_context(), GetType(function.return_type_id)));
  135. } else if (inst.Is<SemIR::SelfParam>()) {
  136. name_id = SemIR::NameId::SelfValue;
  137. } else {
  138. name_id = inst.As<SemIR::Param>().name_id;
  139. }
  140. arg.setName(sem_ir().names().GetIRBaseName(name_id));
  141. }
  142. return llvm_function;
  143. }
  144. auto FileContext::BuildFunctionDefinition(SemIR::FunctionId function_id)
  145. -> void {
  146. const auto& function = sem_ir().functions().Get(function_id);
  147. const auto& body_block_ids = function.body_block_ids;
  148. if (body_block_ids.empty()) {
  149. // Function is probably defined in another file; not an error.
  150. return;
  151. }
  152. llvm::Function* llvm_function = GetFunction(function_id);
  153. FunctionContext function_lowering(*this, llvm_function, vlog_stream_);
  154. const bool has_return_slot = function.return_slot_id.is_valid();
  155. // Add parameters to locals.
  156. // TODO: This duplicates the mapping between sem_ir instructions and LLVM
  157. // function parameters that was already computed in BuildFunctionDecl.
  158. // We should only do that once.
  159. auto implicit_param_refs =
  160. sem_ir().inst_blocks().Get(function.implicit_param_refs_id);
  161. auto param_refs = sem_ir().inst_blocks().Get(function.param_refs_id);
  162. int param_index = 0;
  163. if (has_return_slot) {
  164. function_lowering.SetLocal(function.return_slot_id,
  165. llvm_function->getArg(param_index));
  166. ++param_index;
  167. }
  168. for (auto param_ref_id :
  169. llvm::concat<const SemIR::InstId>(implicit_param_refs, param_refs)) {
  170. auto param_type_id = sem_ir().insts().Get(param_ref_id).type_id();
  171. if (SemIR::GetValueRepr(sem_ir(), param_type_id).kind ==
  172. SemIR::ValueRepr::None) {
  173. function_lowering.SetLocal(
  174. param_ref_id, llvm::PoisonValue::get(GetType(param_type_id)));
  175. } else {
  176. function_lowering.SetLocal(param_ref_id,
  177. llvm_function->getArg(param_index));
  178. ++param_index;
  179. }
  180. }
  181. // Lower all blocks.
  182. for (auto block_id : body_block_ids) {
  183. CARBON_VLOG() << "Lowering " << block_id << "\n";
  184. auto* llvm_block = function_lowering.GetBlock(block_id);
  185. // Keep the LLVM blocks in lexical order.
  186. llvm_block->moveBefore(llvm_function->end());
  187. function_lowering.builder().SetInsertPoint(llvm_block);
  188. function_lowering.LowerBlock(block_id);
  189. }
  190. // LLVM requires that the entry block has no predecessors.
  191. auto* entry_block = &llvm_function->getEntryBlock();
  192. if (entry_block->hasNPredecessorsOrMore(1)) {
  193. auto* new_entry_block = llvm::BasicBlock::Create(
  194. llvm_context(), "entry", llvm_function, entry_block);
  195. llvm::BranchInst::Create(entry_block, new_entry_block);
  196. }
  197. }
  198. auto FileContext::BuildType(SemIR::InstId inst_id) -> llvm::Type* {
  199. switch (inst_id.index) {
  200. case SemIR::BuiltinKind::FloatType.AsInt():
  201. // TODO: Handle different sizes.
  202. return llvm::Type::getDoubleTy(*llvm_context_);
  203. case SemIR::BuiltinKind::IntType.AsInt():
  204. // TODO: Handle different sizes.
  205. return llvm::Type::getInt32Ty(*llvm_context_);
  206. case SemIR::BuiltinKind::BoolType.AsInt():
  207. // TODO: We may want to have different representations for `bool` storage
  208. // (`i8`) versus for `bool` values (`i1`).
  209. return llvm::Type::getInt1Ty(*llvm_context_);
  210. case SemIR::BuiltinKind::FunctionType.AsInt():
  211. case SemIR::BuiltinKind::BoundMethodType.AsInt():
  212. case SemIR::BuiltinKind::NamespaceType.AsInt():
  213. // Return an empty struct as a placeholder.
  214. return llvm::StructType::get(*llvm_context_);
  215. default:
  216. // Handled below.
  217. break;
  218. }
  219. auto inst = sem_ir_->insts().Get(inst_id);
  220. switch (inst.kind()) {
  221. case SemIR::ArrayType::Kind: {
  222. auto array_type = inst.As<SemIR::ArrayType>();
  223. return llvm::ArrayType::get(
  224. GetType(array_type.element_type_id),
  225. sem_ir_->GetArrayBoundValue(array_type.bound_id));
  226. }
  227. case SemIR::ClassType::Kind: {
  228. auto object_repr_id = sem_ir_->classes()
  229. .Get(inst.As<SemIR::ClassType>().class_id)
  230. .object_repr_id;
  231. return GetType(object_repr_id);
  232. }
  233. case SemIR::ConstType::Kind:
  234. return GetType(inst.As<SemIR::ConstType>().inner_id);
  235. case SemIR::PointerType::Kind:
  236. return llvm::PointerType::get(*llvm_context_, /*AddressSpace=*/0);
  237. case SemIR::StructType::Kind: {
  238. auto fields =
  239. sem_ir_->inst_blocks().Get(inst.As<SemIR::StructType>().fields_id);
  240. llvm::SmallVector<llvm::Type*> subtypes;
  241. subtypes.reserve(fields.size());
  242. for (auto field_id : fields) {
  243. auto field = sem_ir_->insts().GetAs<SemIR::StructTypeField>(field_id);
  244. // TODO: Handle recursive types. The restriction for builtins prevents
  245. // recursion while still letting them cache.
  246. CARBON_CHECK(field.field_type_id.index < SemIR::BuiltinKind::ValidCount)
  247. << field.field_type_id;
  248. subtypes.push_back(GetType(field.field_type_id));
  249. }
  250. return llvm::StructType::get(*llvm_context_, subtypes);
  251. }
  252. case SemIR::TupleType::Kind: {
  253. // TODO: Investigate special-casing handling of empty tuples so that they
  254. // can be collectively replaced with LLVM's void, particularly around
  255. // function returns. LLVM doesn't allow declaring variables with a void
  256. // type, so that may require significant special casing.
  257. auto elements =
  258. sem_ir_->type_blocks().Get(inst.As<SemIR::TupleType>().elements_id);
  259. llvm::SmallVector<llvm::Type*> subtypes;
  260. subtypes.reserve(elements.size());
  261. for (auto element_id : elements) {
  262. subtypes.push_back(GetType(element_id));
  263. }
  264. return llvm::StructType::get(*llvm_context_, subtypes);
  265. }
  266. case SemIR::UnboundElementType::Kind: {
  267. // Return an empty struct as a placeholder.
  268. return llvm::StructType::get(*llvm_context_);
  269. }
  270. default: {
  271. CARBON_FATAL() << "Cannot use inst as type: " << inst_id << " " << inst;
  272. }
  273. }
  274. }
  275. } // namespace Carbon::Lower