function_context.cpp 13 KB

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