function_context.cpp 11 KB

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