function_context.cpp 7.6 KB

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