file_context.cpp 52 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273
  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 <memory>
  6. #include <optional>
  7. #include <string>
  8. #include <utility>
  9. #include "clang/CodeGen/ModuleBuilder.h"
  10. #include "common/check.h"
  11. #include "common/pretty_stack_trace_function.h"
  12. #include "common/vlog.h"
  13. #include "llvm/ADT/STLExtras.h"
  14. #include "llvm/ADT/Sequence.h"
  15. #include "llvm/Linker/Linker.h"
  16. #include "llvm/Transforms/Utils/BasicBlockUtils.h"
  17. #include "llvm/Transforms/Utils/ModuleUtils.h"
  18. #include "toolchain/base/kind_switch.h"
  19. #include "toolchain/lower/clang_global_decl.h"
  20. #include "toolchain/lower/constant.h"
  21. #include "toolchain/lower/function_context.h"
  22. #include "toolchain/lower/mangler.h"
  23. #include "toolchain/lower/options.h"
  24. #include "toolchain/lower/specific_coalescer.h"
  25. #include "toolchain/sem_ir/absolute_node_id.h"
  26. #include "toolchain/sem_ir/diagnostic_loc_converter.h"
  27. #include "toolchain/sem_ir/entry_point.h"
  28. #include "toolchain/sem_ir/expr_info.h"
  29. #include "toolchain/sem_ir/file.h"
  30. #include "toolchain/sem_ir/function.h"
  31. #include "toolchain/sem_ir/generic.h"
  32. #include "toolchain/sem_ir/ids.h"
  33. #include "toolchain/sem_ir/inst.h"
  34. #include "toolchain/sem_ir/inst_categories.h"
  35. #include "toolchain/sem_ir/inst_kind.h"
  36. #include "toolchain/sem_ir/pattern.h"
  37. #include "toolchain/sem_ir/stringify.h"
  38. #include "toolchain/sem_ir/typed_insts.h"
  39. namespace Carbon::Lower {
  40. FileContext::FileContext(Context& context, const SemIR::File& sem_ir,
  41. const SemIR::InstNamer* inst_namer,
  42. llvm::raw_ostream* vlog_stream)
  43. : context_(&context),
  44. sem_ir_(&sem_ir),
  45. inst_namer_(inst_namer),
  46. vlog_stream_(vlog_stream),
  47. functions_(LoweredFunctionStore::MakeForOverwrite(sem_ir.functions())),
  48. specific_functions_(sem_ir.specifics(), std::nullopt),
  49. types_(LoweredTypeStore::MakeWithExplicitSize(
  50. sem_ir.constant_values().ConcreteStoreSize(),
  51. sem_ir.constant_values().GetTypeIdTag(), {nullptr, nullptr})),
  52. constants_(LoweredConstantStore::MakeWithExplicitSize(
  53. sem_ir.insts().size(), sem_ir.insts().GetIdTag(), nullptr)),
  54. lowered_specifics_(sem_ir.generics(),
  55. llvm::SmallVector<SemIR::SpecificId>()),
  56. coalescer_(vlog_stream_, sem_ir.specifics()),
  57. vtables_(decltype(vtables_)::MakeForOverwrite(sem_ir.vtables())),
  58. specific_vtables_(sem_ir.specifics(), nullptr) {
  59. // Initialization that relies on invariants of the class.
  60. cpp_code_generator_ = cpp_file() ? cpp_file()->GetCodeGenerator() : nullptr;
  61. CARBON_CHECK(
  62. !cpp_code_generator_ ||
  63. (&cpp_code_generator_->GetModule()->getContext() == &llvm_context()));
  64. CARBON_CHECK(!sem_ir.has_errors(),
  65. "Generating LLVM IR from invalid SemIR::File is unsupported.");
  66. }
  67. // TODO: Move this to lower.cpp.
  68. auto FileContext::PrepareToLower() -> void {
  69. // Lower all types that were required to be complete.
  70. for (auto type_id : sem_ir_->types().complete_types()) {
  71. if (type_id.index >= 0) {
  72. types_.Set(type_id, BuildType(sem_ir_->types().GetTypeInstId(type_id)));
  73. }
  74. }
  75. // Lower function declarations.
  76. for (auto [id, function] : sem_ir_->functions().enumerate()) {
  77. if (id == sem_ir().global_ctor_id()) {
  78. // The global constructor is only lowered when we generate its definition.
  79. // LLVM doesn't allow an internal linkage function to be undefined.
  80. continue;
  81. }
  82. if (function.evaluation_mode == SemIR::Function::EvaluationMode::MustEval) {
  83. // musteval functions are never lowered.
  84. continue;
  85. }
  86. functions_.Set(id, BuildFunctionDecl(id));
  87. }
  88. // TODO: Split vtable declaration creation from definition creation to avoid
  89. // redundant vtable definitions for imported vtables.
  90. for (const auto& [id, vtable] : sem_ir_->vtables().enumerate()) {
  91. const auto& class_info = sem_ir().classes().Get(vtable.class_id);
  92. // Vtables can't be generated for generics, only for their specifics - and
  93. // must be done lazily based on the use of those specifics.
  94. if (!class_info.generic_id.has_value()) {
  95. vtables_.Set(id, BuildVtable(vtable, SemIR::SpecificId::None));
  96. }
  97. }
  98. // Lower constants.
  99. LowerConstants(*this, constants_);
  100. }
  101. // TODO: Move this to lower.cpp.
  102. auto FileContext::LowerDefinitions() -> void {
  103. // Lower global variable definitions.
  104. // TODO: Storing both a `constants_` array and a separate `global_variables_`
  105. // map is redundant.
  106. for (auto inst_id :
  107. sem_ir().inst_blocks().Get(sem_ir().top_inst_block_id())) {
  108. // Only `VarStorage` indicates a global variable declaration in the
  109. // top instruction block.
  110. if (auto var = sem_ir().insts().TryGetAs<SemIR::VarStorage>(inst_id)) {
  111. // Get the global variable declaration. We created this when lowering the
  112. // constant unless the variable is unnamed, in which case we need to
  113. // create it now.
  114. llvm::GlobalVariable* llvm_var = nullptr;
  115. if (auto const_id = sem_ir().constant_values().Get(inst_id);
  116. const_id.is_constant()) {
  117. llvm_var = cast<llvm::GlobalVariable>(GetConstant(const_id, inst_id));
  118. } else {
  119. llvm_var = BuildGlobalVariableDecl(*var);
  120. }
  121. // Convert the declaration of this variable into a definition by adding an
  122. // initializer.
  123. global_variables_.Insert(inst_id, llvm_var);
  124. llvm_var->setInitializer(
  125. llvm::Constant::getNullValue(llvm_var->getValueType()));
  126. }
  127. }
  128. // Lower function definitions.
  129. for (auto [id, fn_info] : sem_ir_->functions().enumerate()) {
  130. // If we created a declaration and the function definition is not imported,
  131. // build a definition.
  132. if (functions_.Get(id) && fn_info.definition_id.has_value() &&
  133. !sem_ir().insts().GetImportSource(fn_info.definition_id).has_value()) {
  134. BuildFunctionDefinition(id);
  135. }
  136. }
  137. // Append `__global_init` to `llvm::global_ctors` to initialize global
  138. // variables.
  139. if (auto global_ctor_id = sem_ir().global_ctor_id();
  140. global_ctor_id.has_value()) {
  141. auto llvm_function = BuildFunctionDecl(global_ctor_id);
  142. functions_.Set(global_ctor_id, llvm_function);
  143. const auto& global_ctor = sem_ir().functions().Get(global_ctor_id);
  144. BuildFunctionBody(global_ctor_id, SemIR::SpecificId::None, global_ctor,
  145. *this, global_ctor);
  146. llvm::appendToGlobalCtors(llvm_module(), llvm_function->llvm_function,
  147. /*Priority=*/0);
  148. }
  149. }
  150. auto FileContext::Finalize() -> void {
  151. if (cpp_code_generator_) {
  152. // Clang code generation should not actually modify the AST, but isn't
  153. // const-correct.
  154. cpp_code_generator_->HandleTranslationUnit(
  155. const_cast<clang::ASTContext&>(cpp_file()->ast_context()));
  156. }
  157. // Find equivalent specifics (from the same generic), replace all uses and
  158. // remove duplicately lowered function definitions.
  159. coalescer_.CoalesceEquivalentSpecifics(lowered_specifics_,
  160. specific_functions_);
  161. }
  162. auto FileContext::GetConstant(SemIR::ConstantId const_id,
  163. SemIR::InstId use_inst_id) -> llvm::Value* {
  164. auto const_inst_id = sem_ir().constant_values().GetInstId(const_id);
  165. auto* const_value = constants_.Get(const_inst_id);
  166. // For value expressions and initializing expressions, the value produced by
  167. // a constant instruction is a value representation of the constant. For
  168. // initializing expressions, `FinishInit` will perform a copy if needed.
  169. switch (auto cat = SemIR::GetExprCategory(sem_ir(), const_inst_id)) {
  170. case SemIR::ExprCategory::Value:
  171. case SemIR::ExprCategory::ReprInitializing:
  172. case SemIR::ExprCategory::InPlaceInitializing:
  173. break;
  174. case SemIR::ExprCategory::DurableRef:
  175. case SemIR::ExprCategory::EphemeralRef:
  176. // Constant reference expressions lower to an address.
  177. return const_value;
  178. case SemIR::ExprCategory::NotExpr:
  179. case SemIR::ExprCategory::Error:
  180. case SemIR::ExprCategory::Pattern:
  181. case SemIR::ExprCategory::Mixed:
  182. case SemIR::ExprCategory::RefTagged:
  183. CARBON_FATAL("Unexpected category {0} for lowered constant {1}", cat,
  184. sem_ir().insts().Get(const_inst_id));
  185. };
  186. auto value_rep = SemIR::ValueRepr::ForType(
  187. sem_ir(), sem_ir().insts().Get(const_inst_id).type_id());
  188. if (value_rep.kind != SemIR::ValueRepr::Pointer) {
  189. return const_value;
  190. }
  191. // The value representation is a pointer. Generate a variable to hold the
  192. // value, or find and reuse an existing one.
  193. if (auto result = global_variables().Lookup(const_inst_id)) {
  194. return result.value();
  195. }
  196. // Include both the name of the constant, if any, and the point of use in
  197. // the name of the variable.
  198. llvm::StringRef const_name;
  199. llvm::StringRef use_name;
  200. if (inst_namer_) {
  201. const_name = inst_namer_->GetUnscopedNameFor(const_inst_id);
  202. if (use_inst_id.has_value()) {
  203. use_name = inst_namer_->GetUnscopedNameFor(use_inst_id);
  204. }
  205. }
  206. // We always need to give the global a name even if the instruction namer
  207. // doesn't have one to use.
  208. if (const_name.empty()) {
  209. const_name = "const";
  210. }
  211. if (use_name.empty()) {
  212. use_name = "anon";
  213. }
  214. llvm::StringRef sep = (use_name[0] == '.') ? "" : ".";
  215. auto* global_variable = new llvm::GlobalVariable(
  216. llvm_module(), GetType(sem_ir().GetPointeeType(value_rep.type_id)),
  217. /*isConstant=*/true, llvm::GlobalVariable::InternalLinkage, const_value,
  218. const_name + sep + use_name);
  219. global_variables_.Insert(const_inst_id, global_variable);
  220. return global_variable;
  221. }
  222. auto FileContext::GetOrCreateFunctionInfo(SemIR::FunctionId function_id,
  223. SemIR::SpecificId specific_id)
  224. -> std::optional<FunctionInfo>& {
  225. // If we have already lowered a declaration of this function, just return it.
  226. auto& result = GetFunctionInfo(function_id, specific_id);
  227. if (!result) {
  228. result = BuildFunctionDecl(function_id, specific_id);
  229. }
  230. return result;
  231. }
  232. // State machine for building a FunctionTypeInfo from SemIR.
  233. //
  234. // The main difficulty this class encapsulates is that each abstraction level
  235. // has different expectations about how the return is reflected in the parameter
  236. // list.
  237. // - In SemIR, if the function has an initializing return form, it has a
  238. // corresponding output parameter at the end of the parameter list.
  239. // - In LLVM IR, if the SemIR has an output parameter _and_ that parameter's
  240. // type has an in-place initializing representation, we emit a corresponding
  241. // `sret` output parameter (and the function's return type is void). By
  242. // convention the output parameter goes at the start of the parameter list.
  243. // - In LLVM debug info, the list of parameter types always starts with the
  244. // return type (which doubles as the type of the return parameter, if there
  245. // is one).
  246. //
  247. // Furthermore, SemIR is designed to eventually support compound return forms,
  248. // in which case there can be multiple output parameters for different pieces of
  249. // the return form, but it's not yet clear how we will lower such functions.
  250. class FileContext::FunctionTypeInfoBuilder {
  251. public:
  252. // Creates a FunctionTypeInfoBuilder that uses the given FileContext, and
  253. // the given specific of the function.
  254. FunctionTypeInfoBuilder(FileContext* context, SemIR::SpecificId specific_id)
  255. : context_(*context), specific_id_(specific_id) {}
  256. // Retrieves various features of `function`'s type useful for constructing the
  257. // `llvm::Type` and `llvm::DISubroutineType` for the `llvm::Function`. If any
  258. // part of the type can't be manifest (eg: incomplete return or parameter
  259. // types), then the result is as if the type was `void()`. Should only be
  260. // called once on a given builder.
  261. auto Build(const SemIR::Function& function) && -> FunctionTypeInfo;
  262. private:
  263. // By convention, state transition methods return false to indicate that
  264. // `Abort` was called. As a convenience, that applies even to methods that
  265. // never call `Abort`, and to `Abort` itself, so that their callers can easily
  266. // propagate the failure.
  267. // Resets the builder to the fallback state `void()`. This puts the builder in
  268. // a state where Finalize can be called, and no other operation should be
  269. // called.
  270. auto Abort() -> bool {
  271. lowered_param_pattern_ids_.clear();
  272. param_types_.clear();
  273. param_di_types_.clear();
  274. return_type_ = nullptr;
  275. SetReturnByCopy(SemIR::TypeId::None);
  276. return false;
  277. }
  278. // Handles the function's return form. The argument can be None, indicating
  279. // that there was no explicitly declared return form.
  280. //
  281. // This should be called before HandleParameter. It delegates to exactly one
  282. // of SetReturnByCopy, SetReturnByReference, SetReturnInPlace, or Abort, and
  283. // returns false if Abort was called.
  284. auto HandleReturnForm(SemIR::InstId return_form_inst_id) -> bool;
  285. // Records that the LLVM function returns by copy, with type `return_type_id`.
  286. // `return_type_id` can be `None`, which is treated as equivalent to the
  287. // default return type `()`.
  288. auto SetReturnByCopy(SemIR::TypeId return_type_id) -> bool {
  289. CARBON_CHECK(return_type_ == nullptr);
  290. CARBON_CHECK(param_di_types_.empty());
  291. auto lowered_return_types = GetLoweredTypes(return_type_id);
  292. return_type_ = lowered_return_types.llvm_ir_type;
  293. param_di_types_.push_back(lowered_return_types.llvm_di_type);
  294. return true;
  295. }
  296. // Records that the LLVM function returns by reference, with type
  297. // `return_type_id`.
  298. auto SetReturnByReference(SemIR::TypeId /*return_type_id*/) -> bool {
  299. return_type_ =
  300. llvm::PointerType::get(context_.llvm_context(), /*AddressSpace=*/0);
  301. // TODO: replace this with a reference type.
  302. param_di_types_.push_back(
  303. context_.context().di_builder().createPointerType(nullptr, 8));
  304. return true;
  305. }
  306. // Records that the LLVM function returns in place, with type
  307. // `return_type_id`.
  308. auto SetReturnInPlace(SemIR::TypeId return_type_id) -> bool {
  309. return_type_ = llvm::Type::getVoidTy(context_.llvm_context());
  310. sret_type_ = context_.GetType(return_type_id);
  311. // We don't add to param_di_types_ because that will be handled by the
  312. // loop over the SemIR parameters.
  313. return true;
  314. }
  315. // Handles the given `Call` parameter, which must be a *ParamPattern inst.
  316. // This should be called on parameter patterns in the order that they should
  317. // appear in the LLVM IR parameter list, so in particular it should be called
  318. // on the `OutParamPattern` (if any) first. It should be called on all `Call`
  319. // parameters; it will determine which parameters belong in the LLVM IR
  320. // parameter list.
  321. //
  322. // This delegates to exactly one of AddLoweredParam, IgnoreParam, or Abort,
  323. // and returns false if Abort was called.
  324. auto HandleParameter(SemIR::InstId param_pattern_id) -> bool;
  325. // Records that the given parameter pattern is lowered to the given
  326. // IR and DI types.
  327. auto AddLoweredParam(SemIR::InstId param_pattern_id, LoweredTypes param_types)
  328. -> bool {
  329. lowered_param_pattern_ids_.push_back(param_pattern_id);
  330. param_types_.push_back(param_types.llvm_ir_type);
  331. param_di_types_.push_back(param_types.llvm_di_type);
  332. return true;
  333. }
  334. // Records that the given parameter pattern is not lowered to an LLVM
  335. // parameter.
  336. auto IgnoreParam(SemIR::InstId param_pattern_id) -> bool {
  337. unused_param_pattern_ids_.push_back(param_pattern_id);
  338. return true;
  339. }
  340. // Builds and returns a FunctionTypeInfo from the accumulated information.
  341. auto Finalize() -> FunctionTypeInfo;
  342. // Returns LLVM IR and DI types for the given SemIR type. This is not a state
  343. // transition. It mostly delegates to context_.GetTypeAndDIType, but treats
  344. // TypeId::None as equivalent to the unit type, and uses an untyped pointer as
  345. // a placeholder DI type if context_ doesn't provide one.
  346. auto GetLoweredTypes(SemIR::TypeId type_id) -> LoweredTypes;
  347. FileContext& context_;
  348. const SemIR::SpecificId specific_id_;
  349. // The types of the parameters in the LLVM IR function. Each one corresponds
  350. // to a SemIR `Call` parameter, but some `Call` parameters may be omitted
  351. // (e.g. if they are stateless) or reordered (e.g. the return parameter, if
  352. // any, always goes first).
  353. llvm::SmallVector<llvm::Type*> param_types_;
  354. // The LLLVM DI representation of the parameter list. As required by LLVM DI
  355. // convention, this starts with the function's return type, and ends with the
  356. // DI representations of param_types_ (in the same order). Note that those
  357. // two ranges may overlap: if the first element of param_types_ represents
  358. // a return parameter, the first element of param_di_types_ corresponds to it
  359. // while also representing the return type.
  360. llvm::SmallVector<llvm::Metadata*> param_di_types_;
  361. // The SemIR function's `Call` param patterns that correspond to param_types_,
  362. // in the same order.
  363. llvm::SmallVector<SemIR::InstId> lowered_param_pattern_ids_;
  364. // Any `Call` param patterns that aren't present in
  365. // reordered_param_pattern_ids_.
  366. llvm::SmallVector<SemIR::InstId> unused_param_pattern_ids_;
  367. // The `index` member of the SemIR function's return parameter, or -1 if it
  368. // has no return parameter. Note that even if the SemIR function has a return
  369. // parameter, the LLVM IR function might not.
  370. int semir_return_param_index_ = -1;
  371. // The LLVM function's return type.
  372. llvm::Type* return_type_ = nullptr;
  373. // If not null, the LLVM function's first parameter should have a `sret`
  374. // attribute with this type.
  375. llvm::Type* sret_type_ = nullptr;
  376. };
  377. auto FileContext::FunctionTypeInfoBuilder::Build(
  378. const SemIR::Function& function) && -> FunctionTypeInfo {
  379. // TODO: For the `Run` entry point, remap return type to i32 if it doesn't
  380. // return a value.
  381. auto call_param_pattern_ids =
  382. context_.sem_ir().inst_blocks().Get(function.call_param_patterns_id);
  383. lowered_param_pattern_ids_.reserve(call_param_pattern_ids.size());
  384. param_types_.reserve(call_param_pattern_ids.size());
  385. param_di_types_.reserve(call_param_pattern_ids.size());
  386. if (!HandleReturnForm(function.return_form_inst_id)) {
  387. return Finalize();
  388. }
  389. if (semir_return_param_index_ >= 0) {
  390. CARBON_CHECK(semir_return_param_index_ ==
  391. static_cast<int>(call_param_pattern_ids.size()) - 1,
  392. "Unexpected parameter order");
  393. // Handle the return parameter first, because it goes first in the LLVM
  394. // convention. We remove it from call_param_pattern_ids so we don't revisit
  395. // it in the subsequent loop.
  396. if (!HandleParameter(call_param_pattern_ids.consume_back())) {
  397. return Finalize();
  398. }
  399. }
  400. for (auto param_pattern_id : call_param_pattern_ids) {
  401. if (!HandleParameter(param_pattern_id)) {
  402. return Finalize();
  403. }
  404. }
  405. return Finalize();
  406. }
  407. auto FileContext::FunctionTypeInfoBuilder::HandleReturnForm(
  408. SemIR::InstId return_form_inst_id) -> bool {
  409. if (!return_form_inst_id.has_value()) {
  410. return SetReturnByCopy(SemIR::TypeId::None);
  411. }
  412. auto return_form_const_id = SemIR::GetConstantValueInSpecific(
  413. context_.sem_ir(), specific_id_, return_form_inst_id);
  414. auto return_form_inst = context_.sem_ir().insts().Get(
  415. context_.sem_ir().constant_values().GetInstId(return_form_const_id));
  416. CARBON_KIND_SWITCH(return_form_inst) {
  417. case CARBON_KIND(SemIR::InitForm init_form): {
  418. CARBON_CHECK(
  419. std::exchange(semir_return_param_index_, init_form.index.index) == -1,
  420. "TODO: Generalize this to support compound return forms");
  421. auto return_type_id =
  422. context_.sem_ir().types().GetTypeIdForTypeConstantId(
  423. SemIR::GetConstantValueInSpecific(
  424. context_.sem_ir(), specific_id_,
  425. init_form.type_component_inst_id));
  426. switch (
  427. SemIR::InitRepr::ForType(context_.sem_ir(), return_type_id).kind) {
  428. case SemIR::InitRepr::InPlace: {
  429. return SetReturnInPlace(return_type_id);
  430. }
  431. case SemIR::InitRepr::ByCopy: {
  432. return SetReturnByCopy(return_type_id);
  433. }
  434. case SemIR::InitRepr::None:
  435. return SetReturnByCopy(SemIR::TypeId::None);
  436. case SemIR::InitRepr::Dependent:
  437. case SemIR::InitRepr::Incomplete:
  438. case SemIR::InitRepr::Abstract:
  439. return Abort();
  440. }
  441. }
  442. case CARBON_KIND(SemIR::RefForm ref_form): {
  443. auto return_type_id =
  444. context_.sem_ir().types().GetTypeIdForTypeConstantId(
  445. SemIR::GetConstantValueInSpecific(
  446. context_.sem_ir(), specific_id_,
  447. ref_form.type_component_inst_id));
  448. return SetReturnByReference(return_type_id);
  449. }
  450. default:
  451. CARBON_FATAL("Unexpected inst kind: {0}", return_form_inst);
  452. }
  453. }
  454. auto FileContext::FunctionTypeInfoBuilder::HandleParameter(
  455. SemIR::InstId param_pattern_id) -> bool {
  456. auto param_pattern = context_.sem_ir().insts().Get(param_pattern_id);
  457. auto param_type_id = ExtractScrutineeType(
  458. context_.sem_ir(),
  459. SemIR::GetTypeOfInstInSpecific(context_.sem_ir(), specific_id_,
  460. param_pattern_id));
  461. // Returns the appropriate LoweredTypes for reference-like parameters.
  462. auto ref_lowered_types = [&]() -> LoweredTypes {
  463. return {.llvm_ir_type = llvm::PointerType::get(context_.llvm_context(),
  464. /*AddressSpace=*/0),
  465. // TODO: replace this with a reference type.
  466. .llvm_di_type = GetLoweredTypes(param_type_id).llvm_di_type};
  467. };
  468. CARBON_CHECK(
  469. !param_type_id.AsConstantId().is_symbolic(),
  470. "Found symbolic type id after resolution when lowering type {0}.",
  471. param_pattern.type_id());
  472. CARBON_KIND_SWITCH(param_pattern) {
  473. case SemIR::RefParamPattern::Kind:
  474. case SemIR::VarParamPattern::Kind: {
  475. return AddLoweredParam(param_pattern_id, ref_lowered_types());
  476. }
  477. case SemIR::OutParamPattern::Kind: {
  478. switch (SemIR::InitRepr::ForType(context_.sem_ir(), param_type_id).kind) {
  479. case SemIR::InitRepr::InPlace:
  480. return AddLoweredParam(param_pattern_id, ref_lowered_types());
  481. case SemIR::InitRepr::ByCopy:
  482. case SemIR::InitRepr::None:
  483. return IgnoreParam(param_pattern_id);
  484. case SemIR::InitRepr::Dependent:
  485. case SemIR::InitRepr::Incomplete:
  486. case SemIR::InitRepr::Abstract:
  487. return Abort();
  488. }
  489. }
  490. case SemIR::ValueParamPattern::Kind: {
  491. switch (auto value_rep =
  492. SemIR::ValueRepr::ForType(context_.sem_ir(), param_type_id);
  493. value_rep.kind) {
  494. case SemIR::ValueRepr::Unknown:
  495. return Abort();
  496. case SemIR::ValueRepr::Dependent:
  497. CARBON_FATAL("Lowering function parameter with dependent type: {0}",
  498. param_pattern);
  499. case SemIR::ValueRepr::None:
  500. return IgnoreParam(param_pattern_id);
  501. case SemIR::ValueRepr::Copy:
  502. case SemIR::ValueRepr::Custom:
  503. case SemIR::ValueRepr::Pointer: {
  504. if (value_rep.type_id.has_value()) {
  505. return AddLoweredParam(param_pattern_id,
  506. GetLoweredTypes(value_rep.type_id));
  507. } else {
  508. return IgnoreParam(param_pattern_id);
  509. }
  510. }
  511. }
  512. }
  513. default:
  514. CARBON_FATAL("Unexpected inst kind: {0}", param_pattern);
  515. }
  516. }
  517. auto FileContext::FunctionTypeInfoBuilder::Finalize() -> FunctionTypeInfo {
  518. CARBON_CHECK(!param_di_types_.empty());
  519. auto& di_builder = context_.context().di_builder();
  520. return {.type = llvm::FunctionType::get(return_type_, param_types_,
  521. /*isVarArg=*/false),
  522. .di_type = di_builder.createSubroutineType(
  523. di_builder.getOrCreateTypeArray(param_di_types_),
  524. llvm::DINode::FlagZero),
  525. .lowered_param_pattern_ids = std::move(lowered_param_pattern_ids_),
  526. .unused_param_pattern_ids = std::move(unused_param_pattern_ids_),
  527. .sret_type = sret_type_};
  528. }
  529. auto FileContext::FunctionTypeInfoBuilder::GetLoweredTypes(
  530. SemIR::TypeId type_id) -> LoweredTypes {
  531. if (!type_id.has_value()) {
  532. return {.llvm_ir_type = llvm::Type::getVoidTy(context_.llvm_context()),
  533. .llvm_di_type = nullptr};
  534. }
  535. auto result = context_.GetTypeAndDIType(type_id);
  536. if (result.llvm_di_type == nullptr) {
  537. // TODO: figure out what type should go here, or ensure this doesn't
  538. // happen.
  539. result.llvm_di_type =
  540. context_.context().di_builder().createPointerType(nullptr, 8);
  541. }
  542. return result;
  543. }
  544. auto FileContext::HandleReferencedCppFunction(clang::FunctionDecl* cpp_decl)
  545. -> llvm::Function* {
  546. // Create the LLVM function (`CodeGenModule::GetOrCreateLLVMFunction()`)
  547. // so that code generation (`CodeGenModule::EmitGlobal()`) would see this
  548. // function name (`CodeGenModule::getMangledName()`), and will generate
  549. // its definition.
  550. auto* function_address = dyn_cast<llvm::Function>(
  551. cpp_code_generator_->GetAddrOfGlobal(CreateGlobalDecl(cpp_decl),
  552. /*isForDefinition=*/false));
  553. CARBON_CHECK(function_address);
  554. return function_address;
  555. }
  556. auto FileContext::HandleReferencedSpecificFunction(
  557. SemIR::FunctionId function_id, SemIR::SpecificId specific_id,
  558. llvm::Type* llvm_type) -> void {
  559. CARBON_CHECK(specific_id.has_value());
  560. // Add this specific function to a list of specific functions whose
  561. // definitions we need to emit.
  562. // TODO: Don't do this if we know this function is emitted as a
  563. // non-discardable symbol in the IR for some other file.
  564. context().AddPendingSpecificFunctionDefinition({.context = this,
  565. .function_id = function_id,
  566. .specific_id = specific_id});
  567. // Create a unique fingerprint for the function type.
  568. // For now, we compute the function type fingerprint only for specifics,
  569. // though we might need it for all functions in order to create a canonical
  570. // fingerprint across translation units.
  571. coalescer_.CreateTypeFingerprint(specific_id, llvm_type);
  572. }
  573. auto FileContext::BuildFunctionDecl(SemIR::FunctionId function_id,
  574. SemIR::SpecificId specific_id)
  575. -> std::optional<FunctionInfo> {
  576. const auto& function = sem_ir().functions().Get(function_id);
  577. // Don't lower generic functions. Note that associated functions in interfaces
  578. // have `Self` in scope, so are implicitly generic functions.
  579. if (function.generic_id.has_value() && !specific_id.has_value()) {
  580. return std::nullopt;
  581. }
  582. // Don't lower builtins.
  583. if (function.builtin_function_kind() != SemIR::BuiltinFunctionKind::None) {
  584. return std::nullopt;
  585. }
  586. // Don't lower C++ functions that use a thunk. We will never reference them
  587. // directly, and their signatures would not be expected to match the
  588. // corresponding C++ function anyway.
  589. if (function.special_function_kind ==
  590. SemIR::Function::SpecialFunctionKind::HasCppThunk) {
  591. return std::nullopt;
  592. }
  593. // TODO: Consider tracking whether the function has been used, and only
  594. // lowering it if it's needed.
  595. auto function_type_info =
  596. FunctionTypeInfoBuilder(this, specific_id).Build(function);
  597. // TODO: For an imported inline function, consider generating an
  598. // `available_externally` definition.
  599. auto linkage = specific_id.has_value() ? llvm::Function::LinkOnceODRLinkage
  600. : llvm::Function::ExternalLinkage;
  601. if (function_id == sem_ir().global_ctor_id()) {
  602. // The global constructor name would collide with global constructors for
  603. // other files in the same package, so use an internal linkage symbol.
  604. linkage = llvm::Function::InternalLinkage;
  605. }
  606. Mangler m(*this);
  607. std::string mangled_name = m.Mangle(function_id, specific_id);
  608. if (auto* existing = llvm_module().getFunction(mangled_name)) {
  609. // We might have already lowered this function while lowering a different
  610. // file. That's OK.
  611. // TODO: Check-fail or maybe diagnose if the two LLVM functions are not
  612. // produced by declarations of the same Carbon function. Name collisions
  613. // between non-private members of the same library should have been
  614. // diagnosed by check if detected, but it's not clear that check will always
  615. // be able to see this problem. In theory, name collisions could also occur
  616. // due to fingerprint collision.
  617. return {{.type = function_type_info.type,
  618. .di_type = function_type_info.di_type,
  619. .lowered_param_pattern_ids =
  620. std::move(function_type_info.lowered_param_pattern_ids),
  621. .unused_param_pattern_ids =
  622. std::move(function_type_info.unused_param_pattern_ids),
  623. .llvm_function = existing}};
  624. }
  625. llvm::Function* llvm_function;
  626. // If this is a C++ function, tell Clang that we referenced it.
  627. if (auto clang_decl_id = sem_ir().functions().Get(function_id).clang_decl_id;
  628. clang_decl_id.has_value()) {
  629. CARBON_CHECK(!specific_id.has_value(),
  630. "Specific functions cannot have C++ definitions");
  631. llvm_function = HandleReferencedCppFunction(
  632. sem_ir().clang_decls().Get(clang_decl_id).key.decl->getAsFunction());
  633. } else {
  634. // If this is a specific function, we may need to do additional work to emit
  635. // its definition.
  636. if (specific_id.has_value()) {
  637. HandleReferencedSpecificFunction(function_id, specific_id,
  638. function_type_info.type);
  639. }
  640. llvm_function = llvm::Function::Create(function_type_info.type, linkage,
  641. mangled_name, llvm_module());
  642. CARBON_CHECK(llvm_function->getName() == mangled_name,
  643. "Mangled name collision: {0}", mangled_name);
  644. // Set up parameters and the return slot.
  645. for (auto [inst_id, arg] :
  646. llvm::zip_equal(function_type_info.lowered_param_pattern_ids,
  647. llvm_function->args())) {
  648. arg.setName(sem_ir().names().GetIRBaseName(
  649. SemIR::GetPrettyNameFromPatternId(sem_ir(), inst_id)));
  650. }
  651. if (function_type_info.sret_type != nullptr) {
  652. auto& return_arg = *llvm_function->args().begin();
  653. return_arg.addAttr(llvm::Attribute::getWithStructRetType(
  654. llvm_context(), function_type_info.sret_type));
  655. }
  656. }
  657. return {{.type = function_type_info.type,
  658. .di_type = function_type_info.di_type,
  659. .lowered_param_pattern_ids =
  660. std::move(function_type_info.lowered_param_pattern_ids),
  661. .unused_param_pattern_ids =
  662. std::move(function_type_info.unused_param_pattern_ids),
  663. .llvm_function = llvm_function}};
  664. }
  665. // Find the file and function ID describing the definition of a function.
  666. static auto GetFunctionDefinition(const SemIR::File* decl_ir,
  667. SemIR::FunctionId function_id)
  668. -> std::pair<const SemIR::File*, SemIR::FunctionId> {
  669. // Find the file containing the definition.
  670. auto decl_id = decl_ir->functions().Get(function_id).definition_id;
  671. if (!decl_id.has_value()) {
  672. // Function is not defined.
  673. return {nullptr, SemIR::FunctionId::None};
  674. }
  675. // Find the function declaration this function was originally imported from.
  676. while (true) {
  677. auto import_inst_id = decl_ir->insts().GetImportSource(decl_id);
  678. if (!import_inst_id.has_value()) {
  679. break;
  680. }
  681. auto import_inst = decl_ir->import_ir_insts().Get(import_inst_id);
  682. decl_ir = decl_ir->import_irs().Get(import_inst.ir_id()).sem_ir;
  683. decl_id = import_inst.inst_id();
  684. }
  685. auto decl_ir_function_id =
  686. decl_ir->insts().GetAs<SemIR::FunctionDecl>(decl_id).function_id;
  687. return {decl_ir, decl_ir_function_id};
  688. }
  689. auto FileContext::BuildFunctionDefinition(SemIR::FunctionId function_id,
  690. SemIR::SpecificId specific_id)
  691. -> void {
  692. auto [definition_ir, definition_ir_function_id] =
  693. GetFunctionDefinition(&sem_ir(), function_id);
  694. if (!definition_ir) {
  695. // Function is probably defined in another file; not an error.
  696. return;
  697. }
  698. const auto& definition_function =
  699. definition_ir->functions().Get(definition_ir_function_id);
  700. BuildFunctionBody(
  701. function_id, specific_id, sem_ir().functions().Get(function_id),
  702. context().GetFileContext(definition_ir), definition_function);
  703. }
  704. auto FileContext::BuildFunctionBody(SemIR::FunctionId function_id,
  705. SemIR::SpecificId specific_id,
  706. const SemIR::Function& declaration_function,
  707. FileContext& definition_context,
  708. const SemIR::Function& definition_function)
  709. -> void {
  710. // On crash, report the function we were lowering.
  711. PrettyStackTraceFunction stack_trace_entry([&](llvm::raw_ostream& output) {
  712. SemIR::DiagnosticLocConverter converter(
  713. &context().tree_and_subtrees_getters(), &sem_ir());
  714. auto converted =
  715. converter.Convert(SemIR::LocId(declaration_function.definition_id),
  716. /*token_only=*/false);
  717. converted.loc.FormatLocation(output);
  718. output << "Lowering function ";
  719. if (specific_id.has_value()) {
  720. output << SemIR::StringifySpecific(sem_ir(), specific_id);
  721. } else {
  722. output << SemIR::StringifyConstantInst(
  723. sem_ir(), declaration_function.definition_id);
  724. }
  725. output << "\n";
  726. // Crash output has a tab indent; try to indent slightly past that.
  727. converted.loc.FormatSnippet(output, /*indent=*/10);
  728. });
  729. // Note that `definition_function` is potentially from a different SemIR::File
  730. // than the one that this file context represents. Any lowering done for
  731. // values derived from `definition_function` should use `definition_context`
  732. // instead of our context.
  733. const auto& definition_ir = definition_context.sem_ir();
  734. auto function_info = GetFunctionInfo(function_id, specific_id);
  735. CARBON_CHECK(function_info && function_info->llvm_function,
  736. "Attempting to define function that was not declared");
  737. const auto& body_block_ids = definition_function.body_block_ids;
  738. CARBON_DCHECK(!body_block_ids.empty(),
  739. "No function body blocks found during lowering.");
  740. // Store which specifics were already lowered (with definitions) for each
  741. // generic.
  742. if (declaration_function.generic_id.has_value() && specific_id.has_value()) {
  743. // TODO: We should track this in the definition context instead so that we
  744. // can deduplicate specifics from different files.
  745. AddLoweredSpecificForGeneric(declaration_function.generic_id, specific_id);
  746. }
  747. // Set attributes on the function definition.
  748. {
  749. llvm::AttrBuilder attr_builder(llvm_context());
  750. attr_builder.addAttribute(llvm::Attribute::NoUnwind);
  751. // TODO: We should take the opt level from the SemIR file; it might not be
  752. // the same for all files in a compilation.
  753. if (context().opt_level() == Lower::OptimizationLevel::None) {
  754. // --optimize=none disables all optimizations for this function.
  755. attr_builder.addAttribute(llvm::Attribute::OptimizeNone);
  756. attr_builder.addAttribute(llvm::Attribute::NoInline);
  757. } else {
  758. // Otherwise, always inline thunks.
  759. if (definition_function.special_function_kind ==
  760. SemIR::Function::SpecialFunctionKind::Thunk) {
  761. attr_builder.addAttribute(llvm::Attribute::AlwaysInline);
  762. }
  763. // Convert --optimize=size into optsize and minsize.
  764. if (context().opt_level() == Lower::OptimizationLevel::Size) {
  765. attr_builder.addAttribute(llvm::Attribute::OptimizeForSize);
  766. attr_builder.addAttribute(llvm::Attribute::MinSize);
  767. }
  768. // TODO: Should we generate an InlineHint for some functions? Perhaps for
  769. // those defined in the API file?
  770. }
  771. function_info->llvm_function->addFnAttrs(attr_builder);
  772. }
  773. auto* subprogram = BuildDISubprogram(declaration_function, *function_info);
  774. FunctionContext function_lowering(
  775. definition_context, function_info->llvm_function, *this, specific_id,
  776. coalescer_.InitializeFingerprintForSpecific(specific_id), subprogram,
  777. vlog_stream_);
  778. auto call_param_ids = definition_ir.inst_blocks().GetOrEmpty(
  779. definition_function.call_params_id);
  780. // Returns the AnyParam inst with the same index as param_pattern_id
  781. // (which must be an AnyParamPattern).
  782. auto param_for_param_pattern =
  783. [&](SemIR::InstId param_pattern_id) -> SemIR::InstId {
  784. auto sem_ir_index = sem_ir()
  785. .insts()
  786. .GetAs<SemIR::AnyParamPattern>(param_pattern_id)
  787. .index.index;
  788. return call_param_ids[sem_ir_index];
  789. };
  790. // Add local variables for the parameters.
  791. for (auto [llvm_index, param_pattern_id] :
  792. llvm::enumerate(function_info->lowered_param_pattern_ids)) {
  793. function_lowering.SetLocal(
  794. param_for_param_pattern(param_pattern_id),
  795. function_info->llvm_function->getArg(llvm_index));
  796. }
  797. // Add local variables for the SemIR parameters that aren't LLVM parameters.
  798. // These shouldn't actually be used, so they're set to poison values.
  799. for (auto [llvm_index, param_pattern_id] :
  800. llvm::enumerate(function_info->unused_param_pattern_ids)) {
  801. auto param_id = param_for_param_pattern(param_pattern_id);
  802. function_lowering.SetLocal(
  803. param_id,
  804. llvm::PoisonValue::get(function_lowering.GetTypeOfInst(param_id)));
  805. }
  806. auto decl_block_id = SemIR::InstBlockId::None;
  807. if (function_id == sem_ir().global_ctor_id()) {
  808. decl_block_id = SemIR::InstBlockId::Empty;
  809. } else {
  810. decl_block_id =
  811. definition_ir.insts()
  812. .GetAs<SemIR::FunctionDecl>(definition_function.latest_decl_id())
  813. .decl_block_id;
  814. }
  815. // Lowers the contents of decl_block_id into the corresponding LLVM block,
  816. // creating it if it doesn't already exist.
  817. auto lower_block = [&](SemIR::InstBlockId block_id) {
  818. CARBON_VLOG("Lowering {0}\n", block_id);
  819. auto* llvm_block = function_lowering.GetBlock(block_id);
  820. // Keep the LLVM blocks in lexical order.
  821. llvm_block->moveBefore(function_info->llvm_function->end());
  822. function_lowering.builder().SetInsertPoint(llvm_block);
  823. function_lowering.LowerBlockContents(block_id);
  824. };
  825. lower_block(decl_block_id);
  826. // If the decl block is empty, reuse it as the first body block. We don't do
  827. // this when the decl block is non-empty so that any branches back to the
  828. // first body block don't also re-execute the decl.
  829. llvm::BasicBlock* block = function_lowering.builder().GetInsertBlock();
  830. if (block->empty() &&
  831. function_lowering.TryToReuseBlock(body_block_ids.front(), block)) {
  832. // Reuse this block as the first block of the function body.
  833. } else {
  834. function_lowering.builder().CreateBr(
  835. function_lowering.GetBlock(body_block_ids.front()));
  836. }
  837. // Lower all blocks.
  838. for (auto block_id : body_block_ids) {
  839. lower_block(block_id);
  840. }
  841. // LLVM requires that the entry block has no predecessors.
  842. auto* entry_block = &function_info->llvm_function->getEntryBlock();
  843. if (entry_block->hasNPredecessorsOrMore(1)) {
  844. auto* new_entry_block = llvm::BasicBlock::Create(
  845. llvm_context(), "entry", function_info->llvm_function, entry_block);
  846. llvm::BranchInst::Create(entry_block, new_entry_block);
  847. }
  848. // Emit fingerprint accumulated inside the function context.
  849. function_lowering.EmitFinalFingerprint();
  850. context().di_builder().finalizeSubprogram(subprogram);
  851. }
  852. auto FileContext::BuildDISubprogram(const SemIR::Function& function,
  853. const FunctionInfo& function_info)
  854. -> llvm::DISubprogram* {
  855. if (!context().di_compile_unit()) {
  856. return nullptr;
  857. }
  858. auto name = sem_ir().names().GetAsStringIfIdentifier(function.name_id);
  859. CARBON_CHECK(name, "Unexpected special name for function: {0}",
  860. function.name_id);
  861. auto loc = GetLocForDI(function.definition_id);
  862. llvm::DISubroutineType* subroutine_type = function_info.di_type;
  863. auto* subprogram = context().di_builder().createFunction(
  864. context().di_compile_unit(), *name,
  865. function_info.llvm_function->getName(),
  866. /*File=*/context().di_builder().createFile(loc.filename, ""),
  867. /*LineNo=*/loc.line_number, subroutine_type,
  868. /*ScopeLine=*/0, llvm::DINode::FlagZero,
  869. llvm::DISubprogram::SPFlagDefinition);
  870. // Add a variable for each parameter, as that is where DWARF debug information
  871. // comes from.
  872. // TODO: this doesn't declare a variable for the output parameter. Is that
  873. // what we want?
  874. for (auto [argument_number, type] :
  875. llvm::enumerate(llvm::drop_begin(subroutine_type->getTypeArray()))) {
  876. context().di_builder().createParameterVariable(
  877. subprogram, "", argument_number + 1, nullptr, 0, type,
  878. /*AlwaysPreserve=*/true);
  879. }
  880. return subprogram;
  881. }
  882. // BuildTypeForInst is used to construct types for FileContext::BuildType below.
  883. // Implementations return the LLVM type for the instruction. This first overload
  884. // is the fallback handler for non-type instructions.
  885. template <typename InstT>
  886. requires(InstT::Kind.is_type() == SemIR::InstIsType::Never)
  887. static auto BuildTypeForInst(FileContext& /*context*/, InstT inst)
  888. -> FileContext::LoweredTypes {
  889. CARBON_FATAL("Cannot use inst as type: {0}", inst);
  890. }
  891. template <typename InstT>
  892. requires(InstT::Kind.is_symbolic_when_type())
  893. static auto BuildTypeForInst(FileContext& context, InstT /*inst*/)
  894. -> FileContext::LoweredTypes {
  895. // Treat non-monomorphized symbolic types as opaque.
  896. return {llvm::StructType::get(context.llvm_context()), nullptr};
  897. }
  898. static auto BuildTypeForInst(FileContext& context, SemIR::ArrayType inst)
  899. -> FileContext::LoweredTypes {
  900. return {llvm::ArrayType::get(
  901. context.GetType(context.sem_ir().types().GetTypeIdForTypeInstId(
  902. inst.element_type_inst_id)),
  903. *context.sem_ir().GetArrayBoundValue(inst.bound_id)),
  904. nullptr};
  905. }
  906. static auto BuildTypeForInst(FileContext& context, SemIR::BoolType /*inst*/)
  907. -> FileContext::LoweredTypes {
  908. // TODO: We may want to have different representations for `bool` storage
  909. // (`i8`) versus for `bool` values (`i1`).
  910. return {llvm::Type::getInt1Ty(context.llvm_context()), nullptr};
  911. }
  912. static auto BuildTypeForInst(FileContext& context, SemIR::ClassType inst)
  913. -> FileContext::LoweredTypes {
  914. auto object_repr_id = context.sem_ir()
  915. .classes()
  916. .Get(inst.class_id)
  917. .GetObjectRepr(context.sem_ir(), inst.specific_id);
  918. return context.GetTypeAndDIType(object_repr_id);
  919. }
  920. template <typename InstT>
  921. requires(SemIR::Internal::HasInstCategory<SemIR::AnyQualifiedType, InstT>)
  922. static auto BuildTypeForInst(FileContext& context, InstT inst)
  923. -> FileContext::LoweredTypes {
  924. return {context.GetType(
  925. context.sem_ir().types().GetTypeIdForTypeInstId(inst.inner_id)),
  926. nullptr};
  927. }
  928. static auto BuildTypeForInst(FileContext& context, SemIR::CustomLayoutType inst)
  929. -> FileContext::LoweredTypes {
  930. auto layout = context.sem_ir().custom_layouts().Get(inst.layout_id);
  931. return {llvm::ArrayType::get(llvm::Type::getInt8Ty(context.llvm_context()),
  932. layout[SemIR::CustomLayoutId::SizeIndex]),
  933. nullptr};
  934. }
  935. static auto BuildTypeForInst(FileContext& context,
  936. SemIR::ImplWitnessAssociatedConstant inst)
  937. -> FileContext::LoweredTypes {
  938. return {context.GetType(inst.type_id), nullptr};
  939. }
  940. static auto BuildTypeForInst(FileContext& /*context*/,
  941. SemIR::ErrorInst /*inst*/)
  942. -> FileContext::LoweredTypes {
  943. // This is a complete type but uses of it should never be lowered.
  944. return {nullptr, nullptr};
  945. }
  946. static auto BuildTypeForInst(FileContext& context, SemIR::FloatType inst)
  947. -> FileContext::LoweredTypes {
  948. return {llvm::Type::getFloatingPointTy(context.llvm_context(),
  949. inst.float_kind.Semantics()),
  950. nullptr};
  951. }
  952. static auto BuildTypeForInst(FileContext& context, SemIR::IntType inst)
  953. -> FileContext::LoweredTypes {
  954. auto width_inst =
  955. context.sem_ir().insts().TryGetAs<SemIR::IntValue>(inst.bit_width_id);
  956. CARBON_CHECK(width_inst, "Can't lower int type with symbolic width");
  957. auto width = context.sem_ir().ints().Get(width_inst->int_id).getZExtValue();
  958. return {llvm::IntegerType::get(context.llvm_context(), width),
  959. context.context().di_builder().createBasicType(
  960. "int", width,
  961. inst.int_kind.is_signed() ? llvm::dwarf::DW_ATE_signed
  962. : llvm::dwarf::DW_ATE_unsigned)};
  963. }
  964. static auto BuildTypeForInst(FileContext& context, SemIR::PointerType /*inst*/)
  965. -> FileContext::LoweredTypes {
  966. return {llvm::PointerType::get(context.llvm_context(), /*AddressSpace=*/0),
  967. nullptr};
  968. }
  969. static auto BuildTypeForInst(FileContext& /*context*/,
  970. SemIR::PatternType /*inst*/)
  971. -> FileContext::LoweredTypes {
  972. CARBON_FATAL("Unexpected pattern type in lowering");
  973. }
  974. static auto BuildTypeForInst(FileContext& context, SemIR::StructType inst)
  975. -> FileContext::LoweredTypes {
  976. auto fields = context.sem_ir().struct_type_fields().Get(inst.fields_id);
  977. llvm::SmallVector<llvm::Type*> subtypes;
  978. subtypes.reserve(fields.size());
  979. for (auto field : fields) {
  980. subtypes.push_back(context.GetType(
  981. context.sem_ir().types().GetTypeIdForTypeInstId(field.type_inst_id)));
  982. }
  983. return {llvm::StructType::get(context.llvm_context(), subtypes), nullptr};
  984. }
  985. static auto BuildTypeForInst(FileContext& context, SemIR::TupleType inst)
  986. -> FileContext::LoweredTypes {
  987. // TODO: Investigate special-casing handling of empty tuples so that they
  988. // can be collectively replaced with LLVM's void, particularly around
  989. // function returns. LLVM doesn't allow declaring variables with a void
  990. // type, so that may require significant special casing.
  991. auto elements = context.sem_ir().inst_blocks().Get(inst.type_elements_id);
  992. llvm::SmallVector<llvm::Type*> subtypes;
  993. subtypes.reserve(elements.size());
  994. for (auto type_id : context.sem_ir().types().GetBlockAsTypeIds(elements)) {
  995. subtypes.push_back(context.GetType(type_id));
  996. }
  997. return {llvm::StructType::get(context.llvm_context(), subtypes), nullptr};
  998. }
  999. static auto BuildTypeForInst(FileContext& context, SemIR::TypeType /*inst*/)
  1000. -> FileContext::LoweredTypes {
  1001. return {context.GetTypeType(), nullptr};
  1002. }
  1003. static auto BuildTypeForInst(FileContext& context, SemIR::FormType /*inst*/)
  1004. -> FileContext::LoweredTypes {
  1005. return {context.GetFormType(), nullptr};
  1006. }
  1007. static auto BuildTypeForInst(FileContext& context, SemIR::VtableType /*inst*/)
  1008. -> FileContext::LoweredTypes {
  1009. return {llvm::Type::getVoidTy(context.llvm_context()), nullptr};
  1010. }
  1011. static auto BuildTypeForInst(FileContext& context,
  1012. SemIR::SpecificFunctionType /*inst*/)
  1013. -> FileContext::LoweredTypes {
  1014. return {llvm::PointerType::get(context.llvm_context(), 0), nullptr};
  1015. }
  1016. template <typename InstT>
  1017. requires(InstT::Kind.template IsAnyOf<
  1018. SemIR::AssociatedEntityType, SemIR::AutoType, SemIR::BoundMethodType,
  1019. SemIR::CharLiteralType, SemIR::CppOverloadSetType,
  1020. SemIR::CppTemplateNameType, SemIR::FacetType,
  1021. SemIR::FloatLiteralType, SemIR::FunctionType,
  1022. SemIR::FunctionTypeWithSelfType, SemIR::GenericClassType,
  1023. SemIR::GenericInterfaceType, SemIR::GenericNamedConstraintType,
  1024. SemIR::InstType, SemIR::IntLiteralType, SemIR::NamespaceType,
  1025. SemIR::RequireSpecificDefinitionType, SemIR::UnboundElementType,
  1026. SemIR::WhereExpr, SemIR::WitnessType>())
  1027. static auto BuildTypeForInst(FileContext& context, InstT /*inst*/)
  1028. -> FileContext::LoweredTypes {
  1029. // Return an empty struct as a placeholder.
  1030. // TODO: Should we model an interface as a witness table, or an associated
  1031. // entity as an index?
  1032. return {llvm::StructType::get(context.llvm_context()), nullptr};
  1033. }
  1034. auto FileContext::BuildType(SemIR::InstId inst_id) -> LoweredTypes {
  1035. // Use overload resolution to select the implementation, producing compile
  1036. // errors when BuildTypeForInst isn't defined for a given instruction.
  1037. CARBON_KIND_SWITCH(sem_ir_->insts().Get(inst_id)) {
  1038. #define CARBON_SEM_IR_INST_KIND(Name) \
  1039. case CARBON_KIND(SemIR::Name inst): { \
  1040. return BuildTypeForInst(*this, inst); \
  1041. }
  1042. #include "toolchain/sem_ir/inst_kind.def"
  1043. }
  1044. }
  1045. auto FileContext::BuildGlobalVariableDecl(SemIR::VarStorage var_storage)
  1046. -> llvm::GlobalVariable* {
  1047. Mangler m(*this);
  1048. auto mangled_name = m.MangleGlobalVariable(var_storage.pattern_id);
  1049. auto linkage = llvm::GlobalVariable::ExternalLinkage;
  1050. // If the variable doesn't have an externally-visible name, demote it to
  1051. // internal linkage and invent a plausible name that shouldn't collide with
  1052. // any of our real manglings.
  1053. if (mangled_name.empty()) {
  1054. linkage = llvm::GlobalVariable::InternalLinkage;
  1055. if (inst_namer_) {
  1056. mangled_name =
  1057. ("var.anon" + inst_namer_->GetUnscopedNameFor(var_storage.pattern_id))
  1058. .str();
  1059. }
  1060. }
  1061. auto* type = GetType(var_storage.type_id);
  1062. return new llvm::GlobalVariable(llvm_module(), type,
  1063. /*isConstant=*/false, linkage,
  1064. /*Initializer=*/nullptr, mangled_name);
  1065. }
  1066. auto FileContext::GetLocForDI(SemIR::InstId inst_id) -> Context::LocForDI {
  1067. auto abs_node_id = GetAbsoluteNodeId(sem_ir_, SemIR::LocId(inst_id)).back();
  1068. if (abs_node_id.check_ir_id() == SemIR::CheckIRId::Cpp) {
  1069. // TODO: Consider asking our cpp_code_generator to map the location to a
  1070. // debug location, in order to use Clang's rules for (eg) macro handling.
  1071. auto loc =
  1072. sem_ir().clang_source_locs().Get(abs_node_id.clang_source_loc_id());
  1073. auto presumed_loc =
  1074. sem_ir().cpp_file()->source_manager().getPresumedLoc(loc);
  1075. return {.filename = presumed_loc.getFilename(),
  1076. .line_number = static_cast<int32_t>(presumed_loc.getLine()),
  1077. .column_number = static_cast<int32_t>(presumed_loc.getColumn())};
  1078. }
  1079. return context().GetLocForDI(abs_node_id);
  1080. }
  1081. auto FileContext::BuildVtable(const SemIR::Vtable& vtable,
  1082. SemIR::SpecificId specific_id)
  1083. -> llvm::GlobalVariable* {
  1084. const auto& class_info = sem_ir().classes().Get(vtable.class_id);
  1085. Mangler m(*this);
  1086. std::string mangled_name = m.MangleVTable(class_info, specific_id);
  1087. if (sem_ir()
  1088. .insts()
  1089. .GetImportSource(class_info.first_owning_decl_id)
  1090. .has_value()) {
  1091. // Emit a declaration of an imported vtable using a(n opaque) pointer type.
  1092. // This doesn't have to match the definition that appears elsewhere, it'll
  1093. // still get merged correctly.
  1094. auto* gv = new llvm::GlobalVariable(
  1095. llvm_module(),
  1096. llvm::PointerType::get(llvm_context(), /*AddressSpace=*/0),
  1097. /*isConstant=*/true, llvm::GlobalValue::ExternalLinkage, nullptr,
  1098. mangled_name);
  1099. gv->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
  1100. return gv;
  1101. }
  1102. auto vtable_inst_block =
  1103. sem_ir().inst_blocks().Get(vtable.virtual_functions_id);
  1104. auto* entry_type = llvm::IntegerType::getInt32Ty(llvm_context());
  1105. auto* table_type = llvm::ArrayType::get(entry_type, vtable_inst_block.size());
  1106. auto* llvm_vtable = new llvm::GlobalVariable(
  1107. llvm_module(), table_type, /*isConstant=*/true,
  1108. llvm::GlobalValue::ExternalLinkage, nullptr, mangled_name);
  1109. auto* i32_type = llvm::IntegerType::getInt32Ty(llvm_context());
  1110. auto* i64_type = llvm::IntegerType::getInt64Ty(llvm_context());
  1111. auto* vtable_const_int =
  1112. llvm::ConstantExpr::getPtrToInt(llvm_vtable, i64_type);
  1113. llvm::SmallVector<llvm::Constant*> vfuncs;
  1114. vfuncs.reserve(vtable_inst_block.size());
  1115. for (auto fn_decl_id : vtable_inst_block) {
  1116. auto [_1, _2, fn_id, fn_specific_id] =
  1117. DecomposeVirtualFunction(sem_ir(), fn_decl_id, specific_id);
  1118. vfuncs.push_back(llvm::ConstantExpr::getTrunc(
  1119. llvm::ConstantExpr::getSub(
  1120. llvm::ConstantExpr::getPtrToInt(
  1121. GetOrCreateFunctionInfo(fn_id, fn_specific_id)->llvm_function,
  1122. i64_type),
  1123. vtable_const_int),
  1124. i32_type));
  1125. }
  1126. llvm_vtable->setInitializer(llvm::ConstantArray::get(table_type, vfuncs));
  1127. llvm_vtable->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
  1128. return llvm_vtable;
  1129. }
  1130. } // namespace Carbon::Lower