file_context.cpp 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452
  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/base/kind_switch.h"
  9. #include "toolchain/lower/constant.h"
  10. #include "toolchain/lower/function_context.h"
  11. #include "toolchain/sem_ir/entry_point.h"
  12. #include "toolchain/sem_ir/file.h"
  13. #include "toolchain/sem_ir/function.h"
  14. #include "toolchain/sem_ir/inst.h"
  15. #include "toolchain/sem_ir/typed_insts.h"
  16. namespace Carbon::Lower {
  17. FileContext::FileContext(llvm::LLVMContext& llvm_context,
  18. llvm::StringRef module_name, const SemIR::File& sem_ir,
  19. const SemIR::InstNamer* inst_namer,
  20. llvm::raw_ostream* vlog_stream)
  21. : llvm_context_(&llvm_context),
  22. llvm_module_(std::make_unique<llvm::Module>(module_name, llvm_context)),
  23. sem_ir_(&sem_ir),
  24. inst_namer_(inst_namer),
  25. vlog_stream_(vlog_stream) {
  26. CARBON_CHECK(!sem_ir.has_errors())
  27. << "Generating LLVM IR from invalid SemIR::File is unsupported.";
  28. }
  29. // TODO: Move this to lower.cpp.
  30. auto FileContext::Run() -> std::unique_ptr<llvm::Module> {
  31. CARBON_CHECK(llvm_module_) << "Run can only be called once.";
  32. // Lower all types that were required to be complete. Note that this may
  33. // leave some entries in `types_` null, if those types were mentioned but not
  34. // used.
  35. types_.resize(sem_ir_->types().size());
  36. for (auto type_id : sem_ir_->complete_types()) {
  37. types_[type_id.index] = BuildType(sem_ir_->types().GetInstId(type_id));
  38. }
  39. // Lower function declarations.
  40. functions_.resize_for_overwrite(sem_ir_->functions().size());
  41. for (auto i : llvm::seq(sem_ir_->functions().size())) {
  42. functions_[i] = BuildFunctionDecl(SemIR::FunctionId(i));
  43. }
  44. // TODO: Lower global variable declarations.
  45. // Lower constants.
  46. constants_.resize(sem_ir_->insts().size());
  47. LowerConstants(*this, constants_);
  48. // Lower function definitions.
  49. for (auto i : llvm::seq(sem_ir_->functions().size())) {
  50. BuildFunctionDefinition(SemIR::FunctionId(i));
  51. }
  52. // TODO: Lower global variable initializers.
  53. return std::move(llvm_module_);
  54. }
  55. auto FileContext::GetGlobal(SemIR::InstId inst_id) -> llvm::Value* {
  56. auto inst = sem_ir().insts().Get(inst_id);
  57. auto const_id = sem_ir().constant_values().Get(inst_id);
  58. if (const_id.is_template()) {
  59. auto const_inst_id = sem_ir().constant_values().GetInstId(const_id);
  60. // For value expressions and initializing expressions, the value produced by
  61. // a constant instruction is a value representation of the constant. For
  62. // initializing expressions, `FinishInit` will perform a copy if needed.
  63. // TODO: Handle reference expression constants.
  64. auto* const_value = constants_[const_inst_id.index];
  65. // If we want a pointer to the constant, materialize a global to hold it.
  66. // TODO: We could reuse the same global if the constant is used more than
  67. // once.
  68. auto value_rep = SemIR::GetValueRepr(sem_ir(), inst.type_id());
  69. if (value_rep.kind == SemIR::ValueRepr::Pointer) {
  70. // Include both the name of the constant, if any, and the point of use in
  71. // the name of the variable.
  72. llvm::StringRef const_name;
  73. llvm::StringRef use_name;
  74. if (inst_namer_) {
  75. const_name = inst_namer_->GetUnscopedNameFor(const_inst_id);
  76. use_name = inst_namer_->GetUnscopedNameFor(inst_id);
  77. }
  78. // We always need to give the global a name even if the instruction namer
  79. // doesn't have one to use.
  80. if (const_name.empty()) {
  81. const_name = "const";
  82. }
  83. if (use_name.empty()) {
  84. use_name = "anon";
  85. }
  86. llvm::StringRef sep = (use_name[0] == '.') ? "" : ".";
  87. return new llvm::GlobalVariable(
  88. llvm_module(), GetType(sem_ir().GetPointeeType(value_rep.type_id)),
  89. /*isConstant=*/true, llvm::GlobalVariable::InternalLinkage,
  90. const_value, const_name + sep + use_name);
  91. }
  92. // Otherwise, we can use the constant value directly.
  93. return const_value;
  94. }
  95. // TODO: For generics, handle references to symbolic constants.
  96. CARBON_FATAL() << "Missing value: " << inst_id << " "
  97. << sem_ir().insts().Get(inst_id);
  98. }
  99. auto FileContext::BuildFunctionDecl(SemIR::FunctionId function_id)
  100. -> llvm::Function* {
  101. const auto& function = sem_ir().functions().Get(function_id);
  102. // Don't lower associated functions.
  103. // TODO: We shouldn't lower any function that has generic parameters.
  104. if (sem_ir().insts().Is<SemIR::InterfaceDecl>(
  105. sem_ir().name_scopes().Get(function.parent_scope_id).inst_id)) {
  106. return nullptr;
  107. }
  108. // Don't lower builtins.
  109. if (function.builtin_function_kind != SemIR::BuiltinFunctionKind::None) {
  110. return nullptr;
  111. }
  112. // Don't lower unused functions.
  113. if (function.return_slot == SemIR::Function::ReturnSlot::NotComputed) {
  114. return nullptr;
  115. }
  116. const bool has_return_slot = function.has_return_slot();
  117. auto implicit_param_refs =
  118. sem_ir().inst_blocks().GetOrEmpty(function.implicit_param_refs_id);
  119. // TODO: Include parameters corresponding to positional parameters.
  120. auto param_refs = sem_ir().inst_blocks().GetOrEmpty(function.param_refs_id);
  121. auto return_type_id = function.declared_return_type(sem_ir());
  122. SemIR::InitRepr return_rep =
  123. return_type_id.is_valid()
  124. ? SemIR::GetInitRepr(sem_ir(), return_type_id)
  125. : SemIR::InitRepr{.kind = SemIR::InitRepr::None};
  126. CARBON_CHECK(return_rep.has_return_slot() == has_return_slot);
  127. llvm::SmallVector<llvm::Type*> param_types;
  128. // TODO: Consider either storing `param_inst_ids` somewhere so that we can
  129. // reuse it from `BuildFunctionDefinition` and when building calls, or factor
  130. // out a mechanism to compute the mapping between parameters and arguments on
  131. // demand.
  132. llvm::SmallVector<SemIR::InstId> param_inst_ids;
  133. auto max_llvm_params =
  134. has_return_slot + implicit_param_refs.size() + param_refs.size();
  135. param_types.reserve(max_llvm_params);
  136. param_inst_ids.reserve(max_llvm_params);
  137. if (has_return_slot) {
  138. param_types.push_back(GetType(return_type_id)->getPointerTo());
  139. param_inst_ids.push_back(function.return_storage_id);
  140. }
  141. for (auto param_ref_id :
  142. llvm::concat<const SemIR::InstId>(implicit_param_refs, param_refs)) {
  143. auto param_type_id =
  144. SemIR::Function::GetParamFromParamRefId(sem_ir(), param_ref_id)
  145. .second.type_id;
  146. switch (auto value_rep = SemIR::GetValueRepr(sem_ir(), param_type_id);
  147. value_rep.kind) {
  148. case SemIR::ValueRepr::Unknown:
  149. CARBON_FATAL()
  150. << "Incomplete parameter type lowering function declaration";
  151. case SemIR::ValueRepr::None:
  152. break;
  153. case SemIR::ValueRepr::Copy:
  154. case SemIR::ValueRepr::Custom:
  155. case SemIR::ValueRepr::Pointer:
  156. param_types.push_back(GetType(value_rep.type_id));
  157. param_inst_ids.push_back(param_ref_id);
  158. break;
  159. }
  160. }
  161. // If the initializing representation doesn't produce a value, set the return
  162. // type to void.
  163. llvm::Type* return_type = return_rep.kind == SemIR::InitRepr::ByCopy
  164. ? GetType(return_type_id)
  165. : llvm::Type::getVoidTy(llvm_context());
  166. std::string mangled_name;
  167. if (SemIR::IsEntryPoint(sem_ir(), function_id)) {
  168. // TODO: Add an implicit `return 0` if `Run` doesn't return `i32`.
  169. mangled_name = "main";
  170. } else if (auto name =
  171. sem_ir().names().GetAsStringIfIdentifier(function.name_id)) {
  172. // TODO: Decide on a name mangling scheme.
  173. mangled_name = *name;
  174. } else {
  175. CARBON_FATAL() << "Unexpected special name for function: "
  176. << function.name_id;
  177. }
  178. llvm::FunctionType* function_type =
  179. llvm::FunctionType::get(return_type, param_types, /*isVarArg=*/false);
  180. auto* llvm_function =
  181. llvm::Function::Create(function_type, llvm::Function::ExternalLinkage,
  182. mangled_name, llvm_module());
  183. // Set up parameters and the return slot.
  184. for (auto [inst_id, arg] :
  185. llvm::zip_equal(param_inst_ids, llvm_function->args())) {
  186. auto name_id = SemIR::NameId::Invalid;
  187. if (inst_id == function.return_storage_id) {
  188. name_id = SemIR::NameId::ReturnSlot;
  189. arg.addAttr(llvm::Attribute::getWithStructRetType(
  190. llvm_context(), GetType(return_type_id)));
  191. } else {
  192. name_id = SemIR::Function::GetParamFromParamRefId(sem_ir(), inst_id)
  193. .second.name_id;
  194. }
  195. arg.setName(sem_ir().names().GetIRBaseName(name_id));
  196. }
  197. return llvm_function;
  198. }
  199. auto FileContext::BuildFunctionDefinition(SemIR::FunctionId function_id)
  200. -> void {
  201. const auto& function = sem_ir().functions().Get(function_id);
  202. const auto& body_block_ids = function.body_block_ids;
  203. if (body_block_ids.empty()) {
  204. // Function is probably defined in another file; not an error.
  205. return;
  206. }
  207. llvm::Function* llvm_function = GetFunction(function_id);
  208. FunctionContext function_lowering(*this, llvm_function, vlog_stream_);
  209. const bool has_return_slot = function.has_return_slot();
  210. // Add parameters to locals.
  211. // TODO: This duplicates the mapping between sem_ir instructions and LLVM
  212. // function parameters that was already computed in BuildFunctionDecl.
  213. // We should only do that once.
  214. auto implicit_param_refs =
  215. sem_ir().inst_blocks().GetOrEmpty(function.implicit_param_refs_id);
  216. auto param_refs = sem_ir().inst_blocks().GetOrEmpty(function.param_refs_id);
  217. int param_index = 0;
  218. if (has_return_slot) {
  219. function_lowering.SetLocal(function.return_storage_id,
  220. llvm_function->getArg(param_index));
  221. ++param_index;
  222. }
  223. for (auto param_ref_id :
  224. llvm::concat<const SemIR::InstId>(implicit_param_refs, param_refs)) {
  225. auto [param_id, param] =
  226. SemIR::Function::GetParamFromParamRefId(sem_ir(), param_ref_id);
  227. // Get the value of the parameter from the function argument.
  228. auto param_type_id = param.type_id;
  229. llvm::Value* param_value = llvm::PoisonValue::get(GetType(param_type_id));
  230. if (SemIR::GetValueRepr(sem_ir(), param_type_id).kind !=
  231. SemIR::ValueRepr::None) {
  232. param_value = llvm_function->getArg(param_index);
  233. ++param_index;
  234. }
  235. // The value of the parameter is the value of the argument.
  236. function_lowering.SetLocal(param_id, param_value);
  237. // Match the portion of the pattern corresponding to the parameter against
  238. // the parameter value. For now this is always a single name binding,
  239. // possibly wrapped in `addr`.
  240. //
  241. // TODO: Support general patterns here.
  242. auto bind_name_id = param_ref_id;
  243. if (auto addr =
  244. sem_ir().insts().TryGetAs<SemIR::AddrPattern>(param_ref_id)) {
  245. bind_name_id = addr->inner_id;
  246. }
  247. auto bind_name = sem_ir().insts().Get(bind_name_id);
  248. // TODO: Should we stop passing compile-time bindings at runtime?
  249. CARBON_CHECK(bind_name.Is<SemIR::AnyBindName>());
  250. function_lowering.SetLocal(bind_name_id, param_value);
  251. }
  252. // Lower all blocks.
  253. for (auto block_id : body_block_ids) {
  254. CARBON_VLOG() << "Lowering " << block_id << "\n";
  255. auto* llvm_block = function_lowering.GetBlock(block_id);
  256. // Keep the LLVM blocks in lexical order.
  257. llvm_block->moveBefore(llvm_function->end());
  258. function_lowering.builder().SetInsertPoint(llvm_block);
  259. function_lowering.LowerBlock(block_id);
  260. }
  261. // LLVM requires that the entry block has no predecessors.
  262. auto* entry_block = &llvm_function->getEntryBlock();
  263. if (entry_block->hasNPredecessorsOrMore(1)) {
  264. auto* new_entry_block = llvm::BasicBlock::Create(
  265. llvm_context(), "entry", llvm_function, entry_block);
  266. llvm::BranchInst::Create(entry_block, new_entry_block);
  267. }
  268. }
  269. static auto BuildTypeForInst(FileContext& context, SemIR::ArrayType inst)
  270. -> llvm::Type* {
  271. return llvm::ArrayType::get(
  272. context.GetType(inst.element_type_id),
  273. context.sem_ir().GetArrayBoundValue(inst.bound_id));
  274. }
  275. static auto BuildTypeForInst(FileContext& context, SemIR::BuiltinInst inst)
  276. -> llvm::Type* {
  277. switch (inst.builtin_inst_kind) {
  278. case SemIR::BuiltinInstKind::Invalid:
  279. case SemIR::BuiltinInstKind::Error:
  280. CARBON_FATAL() << "Unexpected builtin type in lowering.";
  281. case SemIR::BuiltinInstKind::TypeType:
  282. return context.GetTypeType();
  283. case SemIR::BuiltinInstKind::FloatType:
  284. return llvm::Type::getDoubleTy(context.llvm_context());
  285. case SemIR::BuiltinInstKind::IntType:
  286. return llvm::Type::getInt32Ty(context.llvm_context());
  287. case SemIR::BuiltinInstKind::BoolType:
  288. // TODO: We may want to have different representations for `bool`
  289. // storage
  290. // (`i8`) versus for `bool` values (`i1`).
  291. return llvm::Type::getInt1Ty(context.llvm_context());
  292. case SemIR::BuiltinInstKind::StringType:
  293. // TODO: Decide how we want to represent `StringType`.
  294. return llvm::PointerType::get(context.llvm_context(), 0);
  295. case SemIR::BuiltinInstKind::BoundMethodType:
  296. case SemIR::BuiltinInstKind::NamespaceType:
  297. case SemIR::BuiltinInstKind::WitnessType:
  298. // Return an empty struct as a placeholder.
  299. return llvm::StructType::get(context.llvm_context());
  300. }
  301. }
  302. // BuildTypeForInst is used to construct types for FileContext::BuildType below.
  303. // Implementations return the LLVM type for the instruction. This first overload
  304. // is the fallback handler for non-type instructions.
  305. template <typename InstT>
  306. requires(InstT::Kind.is_type() == SemIR::InstIsType::Never)
  307. static auto BuildTypeForInst(FileContext& /*context*/, InstT inst)
  308. -> llvm::Type* {
  309. CARBON_FATAL() << "Cannot use inst as type: " << inst;
  310. }
  311. static auto BuildTypeForInst(FileContext& context, SemIR::ClassType inst)
  312. -> llvm::Type* {
  313. auto object_repr_id =
  314. context.sem_ir().classes().Get(inst.class_id).object_repr_id;
  315. return context.GetType(object_repr_id);
  316. }
  317. static auto BuildTypeForInst(FileContext& context, SemIR::ConstType inst)
  318. -> llvm::Type* {
  319. return context.GetType(inst.inner_id);
  320. }
  321. static auto BuildTypeForInst(FileContext& context, SemIR::FloatType /*inst*/)
  322. -> llvm::Type* {
  323. // TODO: Handle different sizes.
  324. return llvm::Type::getDoubleTy(context.llvm_context());
  325. }
  326. static auto BuildTypeForInst(FileContext& context, SemIR::IntType inst)
  327. -> llvm::Type* {
  328. auto width =
  329. context.sem_ir().insts().TryGetAs<SemIR::IntLiteral>(inst.bit_width_id);
  330. CARBON_CHECK(width) << "Can't lower int type with symbolic width";
  331. return llvm::IntegerType::get(
  332. context.llvm_context(),
  333. context.sem_ir().ints().Get(width->int_id).getZExtValue());
  334. }
  335. static auto BuildTypeForInst(FileContext& context, SemIR::PointerType /*inst*/)
  336. -> llvm::Type* {
  337. return llvm::PointerType::get(context.llvm_context(), /*AddressSpace=*/0);
  338. }
  339. static auto BuildTypeForInst(FileContext& context, SemIR::StructType inst)
  340. -> llvm::Type* {
  341. auto fields = context.sem_ir().inst_blocks().Get(inst.fields_id);
  342. llvm::SmallVector<llvm::Type*> subtypes;
  343. subtypes.reserve(fields.size());
  344. for (auto field_id : fields) {
  345. auto field =
  346. context.sem_ir().insts().GetAs<SemIR::StructTypeField>(field_id);
  347. subtypes.push_back(context.GetType(field.field_type_id));
  348. }
  349. return llvm::StructType::get(context.llvm_context(), subtypes);
  350. }
  351. static auto BuildTypeForInst(FileContext& context, SemIR::TupleType inst)
  352. -> llvm::Type* {
  353. // TODO: Investigate special-casing handling of empty tuples so that they
  354. // can be collectively replaced with LLVM's void, particularly around
  355. // function returns. LLVM doesn't allow declaring variables with a void
  356. // type, so that may require significant special casing.
  357. auto elements = context.sem_ir().type_blocks().Get(inst.elements_id);
  358. llvm::SmallVector<llvm::Type*> subtypes;
  359. subtypes.reserve(elements.size());
  360. for (auto element_id : elements) {
  361. subtypes.push_back(context.GetType(element_id));
  362. }
  363. return llvm::StructType::get(context.llvm_context(), subtypes);
  364. }
  365. template <typename InstT>
  366. requires(InstT::Kind.template IsAnyOf<
  367. SemIR::AssociatedEntityType, SemIR::FunctionType,
  368. SemIR::GenericClassType, SemIR::GenericInterfaceType,
  369. SemIR::InterfaceType, SemIR::UnboundElementType>())
  370. static auto BuildTypeForInst(FileContext& context, InstT /*inst*/)
  371. -> llvm::Type* {
  372. // Return an empty struct as a placeholder.
  373. // TODO: Should we model an interface as a witness table, or an associated
  374. // entity as an index?
  375. return llvm::StructType::get(context.llvm_context());
  376. }
  377. // Treat non-monomorphized symbolic types as opaque.
  378. template <typename InstT>
  379. requires(InstT::Kind.template IsAnyOf<SemIR::BindSymbolicName,
  380. SemIR::InterfaceWitnessAccess>())
  381. static auto BuildTypeForInst(FileContext& context, InstT /*inst*/)
  382. -> llvm::Type* {
  383. return llvm::StructType::get(context.llvm_context());
  384. }
  385. auto FileContext::BuildType(SemIR::InstId inst_id) -> llvm::Type* {
  386. // Use overload resolution to select the implementation, producing compile
  387. // errors when BuildTypeForInst isn't defined for a given instruction.
  388. CARBON_KIND_SWITCH(sem_ir_->insts().Get(inst_id)) {
  389. #define CARBON_SEM_IR_INST_KIND(Name) \
  390. case CARBON_KIND(SemIR::Name inst): { \
  391. return BuildTypeForInst(*this, inst); \
  392. }
  393. #include "toolchain/sem_ir/inst_kind.def"
  394. }
  395. }
  396. } // namespace Carbon::Lower