function_context.cpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332
  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/function_context.h"
  5. #include "common/vlog.h"
  6. #include "toolchain/base/kind_switch.h"
  7. #include "toolchain/sem_ir/file.h"
  8. #include "toolchain/sem_ir/generic.h"
  9. namespace Carbon::Lower {
  10. FunctionContext::FunctionContext(
  11. FileContext& file_context, llvm::Function* function,
  12. FileContext& specific_file_context, SemIR::SpecificId specific_id,
  13. FileContext::SpecificFunctionFingerprint* function_fingerprint,
  14. llvm::DISubprogram* di_subprogram, llvm::raw_ostream* vlog_stream)
  15. : file_context_(&file_context),
  16. function_(function),
  17. specific_file_context_(&specific_file_context),
  18. specific_id_(specific_id),
  19. builder_(file_context.llvm_context(), llvm::ConstantFolder(),
  20. Inserter(file_context.inst_namer())),
  21. di_subprogram_(di_subprogram),
  22. vlog_stream_(vlog_stream),
  23. function_fingerprint_(function_fingerprint) {
  24. function_->setSubprogram(di_subprogram_);
  25. }
  26. auto FunctionContext::GetBlock(SemIR::InstBlockId block_id)
  27. -> llvm::BasicBlock* {
  28. auto result = blocks_.Insert(block_id, [&] {
  29. llvm::StringRef label_name;
  30. if (const auto* inst_namer = file_context_->inst_namer()) {
  31. label_name = inst_namer->GetUnscopedLabelFor(block_id);
  32. }
  33. return llvm::BasicBlock::Create(llvm_context(), label_name, function_);
  34. });
  35. return result.value();
  36. }
  37. auto FunctionContext::TryToReuseBlock(SemIR::InstBlockId block_id,
  38. llvm::BasicBlock* block) -> bool {
  39. if (!blocks_.Insert(block_id, block).is_inserted()) {
  40. return false;
  41. }
  42. if (block == synthetic_block_) {
  43. synthetic_block_ = nullptr;
  44. }
  45. if (const auto* inst_namer = file_context_->inst_namer()) {
  46. block->setName(inst_namer->GetUnscopedLabelFor(block_id));
  47. }
  48. return true;
  49. }
  50. auto FunctionContext::LowerBlockContents(SemIR::InstBlockId block_id) -> void {
  51. for (auto inst_id : sem_ir().inst_blocks().Get(block_id)) {
  52. LowerInst(inst_id);
  53. }
  54. }
  55. // Handles typed instructions for LowerInst. Many instructions lower using
  56. // HandleInst, but others are unsupported or have trivial lowering.
  57. //
  58. // This only calls HandleInst for versions that should have implementations. A
  59. // different approach would be to have the logic below implemented as HandleInst
  60. // overloads. However, forward declarations of HandleInst exist for all `InstT`
  61. // types, which would make getting the right overload resolution complex.
  62. template <typename InstT>
  63. static auto LowerInstHelper(FunctionContext& context, SemIR::InstId inst_id,
  64. InstT inst) -> void {
  65. if constexpr (!InstT::Kind.is_lowered()) {
  66. CARBON_FATAL(
  67. "Encountered an instruction that isn't expected to lower. It's "
  68. "possible that logic needs to be changed in order to stop showing this "
  69. "instruction in lowered contexts. Instruction: {0}",
  70. inst);
  71. } else if constexpr (InstT::Kind.constant_kind() ==
  72. SemIR::InstConstantKind::Always ||
  73. InstT::Kind.constant_kind() ==
  74. SemIR::InstConstantKind::AlwaysUnique) {
  75. CARBON_FATAL("Missing constant value for constant instruction {0}", inst);
  76. } else if constexpr (InstT::Kind.is_type() == SemIR::InstIsType::Always) {
  77. // For instructions that are always of type `type`, produce the trivial
  78. // runtime representation of type `type`.
  79. context.SetLocal(inst_id, context.GetTypeAsValue());
  80. } else {
  81. HandleInst(context, inst_id, inst);
  82. }
  83. }
  84. // TODO: Consider renaming Handle##Name, instead relying on typed_inst overload
  85. // resolution. That would allow putting the nonexistent handler implementations
  86. // in `requires`-style overloads.
  87. // NOLINTNEXTLINE(readability-function-size): The define confuses lint.
  88. auto FunctionContext::LowerInst(SemIR::InstId inst_id) -> void {
  89. // Skip over constants. `FileContext::GetGlobal` lowers them as needed.
  90. if (sem_ir().constant_values().Get(inst_id).is_constant()) {
  91. return;
  92. }
  93. auto inst = sem_ir().insts().Get(inst_id);
  94. CARBON_VLOG("Lowering {0}: {1}\n", inst_id, inst);
  95. builder_.getInserter().SetCurrentInstId(inst_id);
  96. auto debug_loc = GetDebugLoc(inst_id);
  97. if (debug_loc) {
  98. builder_.SetCurrentDebugLocation(debug_loc);
  99. }
  100. CARBON_KIND_SWITCH(inst) {
  101. #define CARBON_SEM_IR_INST_KIND(Name) \
  102. case CARBON_KIND(SemIR::Name typed_inst): { \
  103. LowerInstHelper(*this, inst_id, typed_inst); \
  104. break; \
  105. }
  106. #include "toolchain/sem_ir/inst_kind.def"
  107. }
  108. if (debug_loc) {
  109. builder_.SetCurrentDebugLocation(llvm::DebugLoc());
  110. }
  111. builder_.getInserter().SetCurrentInstId(SemIR::InstId::None);
  112. }
  113. auto FunctionContext::GetBlockArg(SemIR::InstBlockId block_id,
  114. SemIR::TypeId type_id) -> llvm::PHINode* {
  115. llvm::BasicBlock* block = GetBlock(block_id);
  116. // Find the existing phi, if any.
  117. auto phis = block->phis();
  118. if (!phis.empty()) {
  119. CARBON_CHECK(std::next(phis.begin()) == phis.end(),
  120. "Expected at most one phi, found {0}",
  121. std::distance(phis.begin(), phis.end()));
  122. return &*phis.begin();
  123. }
  124. // The number of predecessor slots to reserve.
  125. static constexpr unsigned NumReservedPredecessors = 2;
  126. auto* phi = llvm::PHINode::Create(GetType(type_id), NumReservedPredecessors);
  127. phi->insertInto(block, block->begin());
  128. return phi;
  129. }
  130. auto FunctionContext::GetValue(SemIR::InstId inst_id) -> llvm::Value* {
  131. // All builtins are types, with the same empty lowered value.
  132. if (SemIR::IsSingletonInstId(inst_id)) {
  133. return GetTypeAsValue();
  134. }
  135. if (auto result = locals_.Lookup(inst_id)) {
  136. return result.value();
  137. }
  138. if (auto result = file_context_->global_variables().Lookup(inst_id)) {
  139. return result.value();
  140. }
  141. auto [const_ir, const_id] = GetConstantValueInSpecific(
  142. specific_sem_ir(), specific_id_, sem_ir(), inst_id);
  143. CARBON_CHECK(const_ir == &sem_ir() || const_ir == &specific_sem_ir());
  144. CARBON_CHECK(const_id.is_concrete(),
  145. "Missing value: {0} {1} in {2} has non-concrete value {3}",
  146. inst_id, sem_ir().insts().Get(inst_id), specific_id_, const_id);
  147. // We can only pass on the InstId if it refers to the file in which the
  148. // constant value was provided.
  149. auto* global = GetFileContext(const_ir).GetConstant(
  150. const_id, const_ir == &sem_ir() ? inst_id : SemIR::InstId::None);
  151. AddGlobalToCurrentFingerprint(global);
  152. return global;
  153. }
  154. auto FunctionContext::MakeSyntheticBlock() -> llvm::BasicBlock* {
  155. synthetic_block_ = llvm::BasicBlock::Create(llvm_context(), "", function_);
  156. return synthetic_block_;
  157. }
  158. auto FunctionContext::GetDebugLoc(SemIR::InstId inst_id) -> llvm::DebugLoc {
  159. if (!di_subprogram_) {
  160. return llvm::DebugLoc();
  161. }
  162. auto loc = file_context_->GetLocForDI(inst_id);
  163. if (loc.filename != di_subprogram_->getFile()->getFilename()) {
  164. // Location is from a different file. We can't represent that directly
  165. // within the scope of this function's subprogram, and we don't want to
  166. // generate a new subprogram, so just discard the location information. This
  167. // happens for thunks when emitting the portion of the thunk that is
  168. // duplicated from the original signature.
  169. //
  170. // TODO: Handle this case better.
  171. return llvm::DebugLoc();
  172. }
  173. return llvm::DILocation::get(builder_.getContext(), loc.line_number,
  174. loc.column_number, di_subprogram_);
  175. }
  176. auto FunctionContext::FinishInit(SemIR::TypeId type_id, SemIR::InstId dest_id,
  177. SemIR::InstId source_id) -> void {
  178. switch (SemIR::InitRepr::ForType(sem_ir(), type_id).kind) {
  179. case SemIR::InitRepr::None:
  180. break;
  181. case SemIR::InitRepr::InPlace:
  182. if (sem_ir().constant_values().Get(source_id).is_constant()) {
  183. // When initializing from a constant, emission of the source doesn't
  184. // initialize the destination. Copy the constant value instead.
  185. CopyValue(type_id, source_id, dest_id);
  186. }
  187. break;
  188. case SemIR::InitRepr::ByCopy:
  189. CopyValue(type_id, source_id, dest_id);
  190. break;
  191. case SemIR::InitRepr::Incomplete:
  192. CARBON_FATAL("Lowering aggregate initialization of incomplete type {0}",
  193. sem_ir().types().GetAsInst(type_id));
  194. }
  195. }
  196. auto FunctionContext::GetTypeIdOfInstInSpecific(SemIR::InstId inst_id)
  197. -> std::pair<const SemIR::File*, SemIR::TypeId> {
  198. return SemIR::GetTypeOfInstInSpecific(specific_sem_ir(), specific_id(),
  199. sem_ir(), inst_id);
  200. }
  201. auto FunctionContext::CopyValue(SemIR::TypeId type_id, SemIR::InstId source_id,
  202. SemIR::InstId dest_id) -> void {
  203. switch (auto rep = SemIR::ValueRepr::ForType(sem_ir(), type_id); rep.kind) {
  204. case SemIR::ValueRepr::Unknown:
  205. CARBON_FATAL("Attempt to copy incomplete type");
  206. case SemIR::ValueRepr::None:
  207. break;
  208. case SemIR::ValueRepr::Copy:
  209. builder().CreateStore(GetValue(source_id), GetValue(dest_id));
  210. break;
  211. case SemIR::ValueRepr::Pointer:
  212. CopyObject(type_id, source_id, dest_id);
  213. break;
  214. case SemIR::ValueRepr::Custom:
  215. CARBON_FATAL("TODO: Add support for CopyValue with custom value rep");
  216. }
  217. }
  218. auto FunctionContext::CopyObject(SemIR::TypeId type_id, SemIR::InstId source_id,
  219. SemIR::InstId dest_id) -> void {
  220. const auto& layout = llvm_module().getDataLayout();
  221. auto* type = GetType(type_id);
  222. // TODO: Compute known alignment of the source and destination, which may
  223. // be greater than the alignment computed by LLVM.
  224. auto align = layout.getABITypeAlign(type);
  225. // TODO: Attach !tbaa.struct metadata indicating which portions of the
  226. // type we actually need to copy and which are padding.
  227. builder().CreateMemCpy(GetValue(dest_id), align, GetValue(source_id), align,
  228. layout.getTypeAllocSize(type));
  229. }
  230. auto FunctionContext::Inserter::InsertHelper(
  231. llvm::Instruction* inst, const llvm::Twine& name,
  232. llvm::BasicBlock::iterator insert_pt) const -> void {
  233. llvm::StringRef base_name;
  234. llvm::StringRef separator;
  235. if (inst_namer_ && !inst->getType()->isVoidTy()) {
  236. base_name = inst_namer_->GetUnscopedNameFor(inst_id_);
  237. }
  238. if (!base_name.empty() && !name.isTriviallyEmpty()) {
  239. separator = ".";
  240. }
  241. IRBuilderDefaultInserter::InsertHelper(inst, base_name + separator + name,
  242. insert_pt);
  243. }
  244. auto FunctionContext::AddCallToCurrentFingerprint(SemIR::CheckIRId file_id,
  245. SemIR::FunctionId function_id,
  246. SemIR::SpecificId specific_id)
  247. -> void {
  248. if (!function_fingerprint_) {
  249. return;
  250. }
  251. RawStringOstream os;
  252. // TODO: Replace indexes with info that is translation unit independent.
  253. // Using a string that includes the `FunctionId` string and the index to
  254. // avoid possible collisions. This needs revisiting.
  255. os << "file_id" << file_id.index << "\n";
  256. os << "function_id" << function_id.index << "\n";
  257. current_fingerprint_.common_fingerprint.update(os.TakeStr());
  258. // TODO: Replace index with info that is translation unit independent.
  259. if (specific_id.has_value()) {
  260. current_fingerprint_.specific_fingerprint.update(specific_id.index);
  261. // TODO: Uses -1 as delimiter. This needs revisiting.
  262. current_fingerprint_.specific_fingerprint.update(-1);
  263. function_fingerprint_->calls.push_back(specific_id);
  264. }
  265. }
  266. auto FunctionContext::AddTypeToCurrentFingerprint(llvm::Type* type) -> void {
  267. if (!function_fingerprint_ || !type) {
  268. return;
  269. }
  270. RawStringOstream os;
  271. type->print(os);
  272. os << "\n";
  273. current_fingerprint_.common_fingerprint.update(os.TakeStr());
  274. }
  275. auto FunctionContext::AddGlobalToCurrentFingerprint(llvm::Value* global)
  276. -> void {
  277. if (!function_fingerprint_ || !global) {
  278. return;
  279. }
  280. RawStringOstream os;
  281. global->print(os);
  282. os << "\n";
  283. current_fingerprint_.common_fingerprint.update(os.TakeStr());
  284. }
  285. auto FunctionContext::EmitFinalFingerprint() -> void {
  286. if (!function_fingerprint_) {
  287. return;
  288. }
  289. current_fingerprint_.common_fingerprint.final(
  290. function_fingerprint_->common_fingerprint);
  291. current_fingerprint_.specific_fingerprint.final(
  292. function_fingerprint_->specific_fingerprint);
  293. }
  294. } // namespace Carbon::Lower