file_context.cpp 52 KB

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