file_context.cpp 55 KB

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