function_context.cpp 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212
  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. namespace Carbon::Lower {
  9. FunctionContext::FunctionContext(FileContext& file_context,
  10. llvm::Function* function,
  11. llvm::DISubprogram* di_subprogram,
  12. llvm::raw_ostream* vlog_stream)
  13. : file_context_(&file_context),
  14. function_(function),
  15. builder_(file_context.llvm_context(), llvm::ConstantFolder(),
  16. Inserter(file_context.inst_namer())),
  17. di_subprogram_(di_subprogram),
  18. vlog_stream_(vlog_stream) {
  19. function_->setSubprogram(di_subprogram_);
  20. }
  21. auto FunctionContext::GetBlock(SemIR::InstBlockId block_id)
  22. -> llvm::BasicBlock* {
  23. auto result = blocks_.Insert(block_id, [&] {
  24. llvm::StringRef label_name;
  25. if (const auto* inst_namer = file_context_->inst_namer()) {
  26. label_name = inst_namer->GetUnscopedLabelFor(block_id);
  27. }
  28. return llvm::BasicBlock::Create(llvm_context(), label_name, function_);
  29. });
  30. return result.value();
  31. }
  32. auto FunctionContext::TryToReuseBlock(SemIR::InstBlockId block_id,
  33. llvm::BasicBlock* block) -> bool {
  34. if (!blocks_.Insert(block_id, block).is_inserted()) {
  35. return false;
  36. }
  37. if (block == synthetic_block_) {
  38. synthetic_block_ = nullptr;
  39. }
  40. if (const auto* inst_namer = file_context_->inst_namer()) {
  41. block->setName(inst_namer->GetUnscopedLabelFor(block_id));
  42. }
  43. return true;
  44. }
  45. auto FunctionContext::LowerBlock(SemIR::InstBlockId block_id) -> void {
  46. for (auto inst_id : sem_ir().inst_blocks().Get(block_id)) {
  47. LowerInst(inst_id);
  48. }
  49. }
  50. // Handles typed instructions for LowerInst. Many instructions lower using
  51. // HandleInst, but others are unsupported or have trivial lowering.
  52. //
  53. // This only calls HandleInst for versions that should have implementations. A
  54. // different approach would be to have the logic below implemented as HandleInst
  55. // overloads. However, forward declarations of HandleInst exist for all `InstT`
  56. // types, which would make getting the right overload resolution complex.
  57. template <typename InstT>
  58. static auto LowerInstHelper(FunctionContext& context, SemIR::InstId inst_id,
  59. InstT inst) {
  60. if constexpr (!InstT::Kind.is_lowered()) {
  61. CARBON_FATAL()
  62. << "Encountered an instruction that isn't expected to lower. It's "
  63. "possible that logic needs to be changed in order to stop "
  64. "showing this instruction in lowered contexts. Instruction: "
  65. << inst;
  66. } else if constexpr (InstT::Kind.constant_kind() ==
  67. SemIR::InstConstantKind::Always) {
  68. CARBON_FATAL() << "Missing constant value for constant instruction "
  69. << inst;
  70. } else if constexpr (InstT::Kind.is_type() == SemIR::InstIsType::Always) {
  71. // For instructions that are always of type `type`, produce the trivial
  72. // runtime representation of type `type`.
  73. context.SetLocal(inst_id, context.GetTypeAsValue());
  74. } else {
  75. HandleInst(context, inst_id, inst);
  76. }
  77. }
  78. // TODO: Consider renaming Handle##Name, instead relying on typed_inst overload
  79. // resolution. That would allow putting the nonexistent handler implementations
  80. // in `requires`-style overloads.
  81. // NOLINTNEXTLINE(readability-function-size): The define confuses lint.
  82. auto FunctionContext::LowerInst(SemIR::InstId inst_id) -> void {
  83. // Skip over constants. `FileContext::GetGlobal` lowers them as needed.
  84. if (sem_ir().constant_values().Get(inst_id).is_constant()) {
  85. return;
  86. }
  87. auto inst = sem_ir().insts().Get(inst_id);
  88. CARBON_VLOG() << "Lowering " << inst_id << ": " << inst << "\n";
  89. builder_.getInserter().SetCurrentInstId(inst_id);
  90. auto loc = file_context_->GetDiagnosticLoc(inst_id);
  91. builder_.SetCurrentDebugLocation(
  92. llvm::DILocation::get(builder_.getContext(), loc.line_number,
  93. loc.column_number, di_subprogram_));
  94. CARBON_KIND_SWITCH(inst) {
  95. #define CARBON_SEM_IR_INST_KIND(Name) \
  96. case CARBON_KIND(SemIR::Name typed_inst): { \
  97. LowerInstHelper(*this, inst_id, typed_inst); \
  98. break; \
  99. }
  100. #include "toolchain/sem_ir/inst_kind.def"
  101. }
  102. builder_.getInserter().SetCurrentInstId(SemIR::InstId::Invalid);
  103. builder_.SetCurrentDebugLocation(llvm::DebugLoc());
  104. }
  105. auto FunctionContext::GetBlockArg(SemIR::InstBlockId block_id,
  106. SemIR::TypeId type_id) -> llvm::PHINode* {
  107. llvm::BasicBlock* block = GetBlock(block_id);
  108. // Find the existing phi, if any.
  109. auto phis = block->phis();
  110. if (!phis.empty()) {
  111. CARBON_CHECK(std::next(phis.begin()) == phis.end())
  112. << "Expected at most one phi, found "
  113. << std::distance(phis.begin(), phis.end());
  114. return &*phis.begin();
  115. }
  116. // The number of predecessor slots to reserve.
  117. static constexpr unsigned NumReservedPredecessors = 2;
  118. auto* phi = llvm::PHINode::Create(GetType(type_id), NumReservedPredecessors);
  119. phi->insertInto(block, block->begin());
  120. return phi;
  121. }
  122. auto FunctionContext::MakeSyntheticBlock() -> llvm::BasicBlock* {
  123. synthetic_block_ = llvm::BasicBlock::Create(llvm_context(), "", function_);
  124. return synthetic_block_;
  125. }
  126. auto FunctionContext::FinishInit(SemIR::TypeId type_id, SemIR::InstId dest_id,
  127. SemIR::InstId source_id) -> void {
  128. switch (SemIR::InitRepr::ForType(sem_ir(), type_id).kind) {
  129. case SemIR::InitRepr::None:
  130. break;
  131. case SemIR::InitRepr::InPlace:
  132. if (sem_ir().constant_values().Get(source_id).is_constant()) {
  133. // When initializing from a constant, emission of the source doesn't
  134. // initialize the destination. Copy the constant value instead.
  135. CopyValue(type_id, source_id, dest_id);
  136. }
  137. break;
  138. case SemIR::InitRepr::ByCopy:
  139. CopyValue(type_id, source_id, dest_id);
  140. break;
  141. case SemIR::InitRepr::Incomplete:
  142. CARBON_FATAL() << "Lowering aggregate initialization of incomplete type "
  143. << sem_ir().types().GetAsInst(type_id);
  144. }
  145. }
  146. auto FunctionContext::CopyValue(SemIR::TypeId type_id, SemIR::InstId source_id,
  147. SemIR::InstId dest_id) -> void {
  148. switch (auto rep = SemIR::ValueRepr::ForType(sem_ir(), type_id); rep.kind) {
  149. case SemIR::ValueRepr::Unknown:
  150. CARBON_FATAL() << "Attempt to copy incomplete type";
  151. case SemIR::ValueRepr::None:
  152. break;
  153. case SemIR::ValueRepr::Copy:
  154. builder().CreateStore(GetValue(source_id), GetValue(dest_id));
  155. break;
  156. case SemIR::ValueRepr::Pointer:
  157. CopyObject(type_id, source_id, dest_id);
  158. break;
  159. case SemIR::ValueRepr::Custom:
  160. CARBON_FATAL() << "TODO: Add support for CopyValue with custom value rep";
  161. }
  162. }
  163. auto FunctionContext::CopyObject(SemIR::TypeId type_id, SemIR::InstId source_id,
  164. SemIR::InstId dest_id) -> void {
  165. const auto& layout = llvm_module().getDataLayout();
  166. auto* type = GetType(type_id);
  167. // TODO: Compute known alignment of the source and destination, which may
  168. // be greater than the alignment computed by LLVM.
  169. auto align = layout.getABITypeAlign(type);
  170. // TODO: Attach !tbaa.struct metadata indicating which portions of the
  171. // type we actually need to copy and which are padding.
  172. builder().CreateMemCpy(GetValue(dest_id), align, GetValue(source_id), align,
  173. layout.getTypeAllocSize(type));
  174. }
  175. auto FunctionContext::Inserter::InsertHelper(
  176. llvm::Instruction* inst, const llvm::Twine& name,
  177. llvm::BasicBlock::iterator insert_pt) const -> void {
  178. llvm::StringRef base_name;
  179. llvm::StringRef separator;
  180. if (inst_namer_ && !inst->getType()->isVoidTy()) {
  181. base_name = inst_namer_->GetUnscopedNameFor(inst_id_);
  182. }
  183. if (!base_name.empty() && !name.isTriviallyEmpty()) {
  184. separator = ".";
  185. }
  186. IRBuilderDefaultInserter::InsertHelper(inst, base_name + separator + name,
  187. insert_pt);
  188. }
  189. } // namespace Carbon::Lower