function_context.h 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322
  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. #ifndef CARBON_TOOLCHAIN_LOWER_FUNCTION_CONTEXT_H_
  5. #define CARBON_TOOLCHAIN_LOWER_FUNCTION_CONTEXT_H_
  6. #include "common/map.h"
  7. #include "common/raw_string_ostream.h"
  8. #include "llvm/IR/IRBuilder.h"
  9. #include "llvm/IR/LLVMContext.h"
  10. #include "llvm/IR/Module.h"
  11. #include "toolchain/lower/file_context.h"
  12. #include "toolchain/sem_ir/file.h"
  13. #include "toolchain/sem_ir/ids.h"
  14. namespace Carbon::Lower {
  15. // Context and shared functionality for lowering handlers that produce an
  16. // `llvm::Function` definition.
  17. class FunctionContext {
  18. public:
  19. // `function` must not be null. `function_fingerprint` and `di_subprogram` may
  20. // be null (see members).
  21. explicit FunctionContext(
  22. FileContext& file_context, llvm::Function* function,
  23. FileContext& specific_file_context, SemIR::SpecificId specific_id,
  24. FileContext::SpecificFunctionFingerprint* function_fingerprint,
  25. llvm::DISubprogram* di_subprogram, llvm::raw_ostream* vlog_stream);
  26. // Describes a function's body fingerprint while creating the function body.
  27. // The final fingerprint is stored in the `FileContext` as a
  28. // `SpecificFunctionFingerprint`.
  29. //
  30. // Create two function fingerprints, where both fingerprints include data
  31. // that's evaluated (and hence lowered) differently based on the
  32. // `SpecificId`. `common_fingerprint` includes global values, types
  33. // and `FunctionId` for functions called inside the function body.
  34. // `specific_fingerprint` includes `SpecificId`s for functions called.
  35. //
  36. // For two specifics of the same generic:
  37. // - If `common_fingerprint` is different, the specifics cannot be coalesced.
  38. // - If `common_fingerprint` and `specific_fingerprint` are the
  39. // same, the specifics can be coalesced without additional checks.
  40. // - If `common_fingerprint` is the same but `specific_fingerprint` is
  41. // different, additional checks are needed, i.e. inspecting the non-hashed
  42. // `SpecificId`s.
  43. //
  44. // TODO: Consider optimizations for repeated entries in both fingerprints.
  45. struct LoweringFunctionFingerprint {
  46. llvm::BLAKE3 common_fingerprint;
  47. llvm::BLAKE3 specific_fingerprint;
  48. };
  49. // Returns a basic block corresponding to the start of the given semantics
  50. // block, and enqueues it for emission.
  51. auto GetBlock(SemIR::InstBlockId block_id) -> llvm::BasicBlock*;
  52. // If we have not yet allocated a `BasicBlock` for this `block_id`, set it to
  53. // `block`, and enqueue `block_id` for emission. Returns whether we set the
  54. // block.
  55. auto TryToReuseBlock(SemIR::InstBlockId block_id, llvm::BasicBlock* block)
  56. -> bool;
  57. // Builds LLVM IR for the sequence of instructions in `block_id`.
  58. auto LowerBlockContents(SemIR::InstBlockId block_id) -> void;
  59. // Builds LLVM IR for the specified instruction.
  60. auto LowerInst(SemIR::InstId inst_id) -> void;
  61. // Returns a phi node corresponding to the block argument of the given basic
  62. // block.
  63. auto GetBlockArg(SemIR::InstBlockId block_id, SemIR::TypeId type_id)
  64. -> llvm::PHINode*;
  65. // Returns a value for the given instruction.
  66. auto GetValue(SemIR::InstId inst_id) -> llvm::Value*;
  67. // Sets the value for the given instruction.
  68. auto SetLocal(SemIR::InstId inst_id, llvm::Value* value) -> void {
  69. bool added = locals_.Insert(inst_id, value).is_inserted();
  70. CARBON_CHECK(added, "Duplicate local insert: {0} {1}", inst_id,
  71. sem_ir().insts().Get(inst_id));
  72. }
  73. // Gets a callable's function.
  74. auto GetFunction(SemIR::FunctionId function_id) -> llvm::Function* {
  75. return file_context_->GetFunction(function_id);
  76. }
  77. // Gets or creates a callable's function.
  78. auto GetOrCreateFunction(SemIR::FunctionId function_id,
  79. SemIR::SpecificId specific_id) -> llvm::Function* {
  80. return file_context_->GetOrCreateFunction(function_id, specific_id);
  81. }
  82. // Builds LLVM function type information for the specified function.
  83. auto BuildFunctionTypeInfo(const SemIR::Function& function,
  84. SemIR::SpecificId specific_id)
  85. -> FileContext::FunctionTypeInfo {
  86. return file_context_->BuildFunctionTypeInfo(function, specific_id);
  87. }
  88. // Returns a lowered type for the given type_id.
  89. auto GetType(SemIR::TypeId type_id) -> llvm::Type* {
  90. return file_context_->GetType(type_id);
  91. }
  92. // Returns the type of the given instruction in the current specific.
  93. auto GetTypeOfInstInSpecific(SemIR::InstId inst_id) -> llvm::Type* {
  94. auto [type_file, type_id] = GetTypeIdOfInstInSpecific(inst_id);
  95. auto* type = GetFileContext(type_file).GetType(type_id);
  96. AddTypeToCurrentFingerprint(type);
  97. return type;
  98. }
  99. // Returns the type of the given instruction in the current specific.
  100. // TODO: Each caller of this should add information to the fingerprint
  101. // indicating what information they used from the type.
  102. auto GetTypeIdOfInstInSpecific(SemIR::InstId inst_id)
  103. -> std::pair<const SemIR::File*, SemIR::TypeId>;
  104. // Returns a lowered value to use for a value of type `type`.
  105. auto GetTypeAsValue() -> llvm::Value* {
  106. return file_context_->GetTypeAsValue();
  107. }
  108. // Returns a lowered value to use for a value of int literal type.
  109. auto GetIntLiteralAsValue() -> llvm::Constant* {
  110. return file_context_->GetIntLiteralAsValue();
  111. }
  112. // Returns the instruction immediately after all the existing static allocas.
  113. // This is the insert point for future static allocas.
  114. auto GetInstructionAfterAllocas() const -> llvm::Instruction* {
  115. return after_allocas_;
  116. }
  117. // Sets the instruction after static allocas. This should be called once,
  118. // after the first alloca is created.
  119. auto SetInstructionAfterAllocas(llvm::Instruction* after_allocas) -> void {
  120. CARBON_CHECK(!after_allocas_);
  121. after_allocas_ = after_allocas;
  122. }
  123. // Create a synthetic block that corresponds to no SemIR::InstBlockId. Such
  124. // a block should only ever have a single predecessor, and is used when we
  125. // need multiple `llvm::BasicBlock`s to model the linear control flow in a
  126. // single SemIR::File block.
  127. auto MakeSyntheticBlock() -> llvm::BasicBlock*;
  128. // Determine whether block is the most recently created synthetic block.
  129. auto IsCurrentSyntheticBlock(llvm::BasicBlock* block) -> bool {
  130. return synthetic_block_ == block;
  131. }
  132. // Returns the debug location to associate with the specified instruction.
  133. auto GetDebugLoc(SemIR::InstId inst_id) -> llvm::DebugLoc;
  134. // After emitting an initializer `init_id`, finishes performing the
  135. // initialization of `dest_id` from that initializer. This is a no-op if the
  136. // initialization was performed in-place, and otherwise performs a store or a
  137. // copy.
  138. auto FinishInit(SemIR::TypeId type_id, SemIR::InstId dest_id,
  139. SemIR::InstId source_id) -> void;
  140. // When fingerprinting for a specific, adds the call, found in the function
  141. // body, to <function_id, specific_id>. `function_id` and `specific_id` are
  142. // IDs within the file identified by `function_file_id`.
  143. auto AddCallToCurrentFingerprint(SemIR::CheckIRId file_id,
  144. SemIR::FunctionId function_id,
  145. SemIR::SpecificId specific_id) -> void;
  146. // When fingerprinting for a specific, adds the type.
  147. auto AddTypeToCurrentFingerprint(llvm::Type* type) -> void;
  148. // Emits the final function fingerprints. Only called when function lowering
  149. // is complete.
  150. auto EmitFinalFingerprint() -> void;
  151. // Returns the FileContext to use for lowering in the given file.
  152. auto GetFileContext(const SemIR::File* file) -> FileContext& {
  153. // Avoid hash table lookup for the expected files.
  154. if (file == &sem_ir()) {
  155. return *file_context_;
  156. }
  157. if (file == &specific_sem_ir()) {
  158. return *specific_file_context_;
  159. }
  160. return file_context_->context().GetFileContext(file);
  161. }
  162. auto llvm_context() -> llvm::LLVMContext& {
  163. return file_context_->llvm_context();
  164. }
  165. auto llvm_module() -> llvm::Module& { return file_context_->llvm_module(); }
  166. auto llvm_function() -> llvm::Function& { return *function_; }
  167. auto builder() -> llvm::IRBuilderBase& { return builder_; }
  168. auto sem_ir() -> const SemIR::File& { return file_context_->sem_ir(); }
  169. // The file context for the file that `specific_id()` is within.
  170. auto specific_file_context() -> FileContext& {
  171. return *specific_file_context_;
  172. }
  173. // The file that `specific_id()` is within.
  174. auto specific_sem_ir() -> const SemIR::File& {
  175. return specific_file_context_->sem_ir();
  176. }
  177. // The specific ID for the function that is being lowered. Note that this is
  178. // an ID from `specific_sem_ir()`, not from `sem_ir()`.
  179. auto specific_id() -> SemIR::SpecificId { return specific_id_; }
  180. // TODO: could template on BuiltinFunctionKind if more format
  181. // globals are eventually needed.
  182. auto printf_int_format_string() -> llvm::Value* {
  183. auto* format_string = file_context_->printf_int_format_string();
  184. if (!format_string) {
  185. format_string = builder().CreateGlobalString("%d\n", "printf.int.format");
  186. file_context_->SetPrintfIntFormatString(format_string);
  187. }
  188. return format_string;
  189. }
  190. private:
  191. // Custom instruction inserter for our IR builder. Automatically names
  192. // instructions.
  193. class Inserter : public llvm::IRBuilderDefaultInserter {
  194. public:
  195. explicit Inserter(const SemIR::InstNamer* inst_namer)
  196. : inst_namer_(inst_namer) {}
  197. // Sets the instruction we are currently emitting.
  198. auto SetCurrentInstId(SemIR::InstId inst_id) -> void { inst_id_ = inst_id; }
  199. private:
  200. auto InsertHelper(llvm::Instruction* inst, const llvm::Twine& name,
  201. llvm::BasicBlock::iterator insert_pt) const
  202. -> void override;
  203. // The instruction namer.
  204. const SemIR::InstNamer* inst_namer_;
  205. // The current instruction ID.
  206. SemIR::InstId inst_id_ = SemIR::InstId::None;
  207. };
  208. // Emits a value copy for type `type_id` from `source_id` to `dest_id`.
  209. // `source_id` must produce a value representation for `type_id`, and
  210. // `dest_id` must be a pointer to a `type_id` object.
  211. auto CopyValue(SemIR::TypeId type_id, SemIR::InstId source_id,
  212. SemIR::InstId dest_id) -> void;
  213. // Emits an object representation copy for type `type_id` from `source_id` to
  214. // `dest_id`. `source_id` and `dest_id` must produce pointers to `type_id`
  215. // objects.
  216. auto CopyObject(SemIR::TypeId type_id, SemIR::InstId source_id,
  217. SemIR::InstId dest_id) -> void;
  218. // When fingerprinting for a specific, adds the global.
  219. auto AddGlobalToCurrentFingerprint(llvm::Value* global) -> void;
  220. // Context for lowering in the file that contains this function's
  221. // instructions.
  222. FileContext* file_context_;
  223. // The IR function we're generating.
  224. llvm::Function* function_;
  225. // Context for lowering in the file that contains our `specific_id_`. Note
  226. // that this is a different file than the one referred to by `file_context_`
  227. // if we are lowering a specific that was generated for a generic function
  228. // defined in a different file.
  229. FileContext* specific_file_context_;
  230. // The specific id, if the function is a specific.
  231. SemIR::SpecificId specific_id_;
  232. // Builder for creating code in this function. The insertion point is held at
  233. // the location of the current SemIR instruction.
  234. llvm::IRBuilder<llvm::ConstantFolder, Inserter> builder_;
  235. // The instruction after all allocas. This is used as the insert point for new
  236. // allocas.
  237. llvm::Instruction* after_allocas_ = nullptr;
  238. llvm::DISubprogram* di_subprogram_;
  239. // The optional vlog stream.
  240. llvm::raw_ostream* vlog_stream_;
  241. // This is initialized and populated while lowering a specific function.
  242. // When complete, this is used to complete the function_fingerprint_.
  243. LoweringFunctionFingerprint current_fingerprint_;
  244. // The accumulated fingerprint is owned by the FileContext and passed into
  245. // the FunctionContext. The function fingerprint is currently only built for
  246. // specific functions, otherwise, this will be nullptr.
  247. FileContext::SpecificFunctionFingerprint* function_fingerprint_;
  248. // Maps a function's SemIR::File blocks to lowered blocks.
  249. Map<SemIR::InstBlockId, llvm::BasicBlock*> blocks_;
  250. // The synthetic block we most recently created. May be null if there is no
  251. // such block.
  252. llvm::BasicBlock* synthetic_block_ = nullptr;
  253. // Maps a function's SemIR::File instructions to lowered values.
  254. Map<SemIR::InstId, llvm::Value*> locals_;
  255. };
  256. // Provides handlers for instructions that occur in a FunctionContext. Although
  257. // this is declared for all instructions, it should only be defined for
  258. // instructions which are non-constant and not always typed. See
  259. // `FunctionContext::LowerInst` for how this is used.
  260. #define CARBON_SEM_IR_INST_KIND(Name) \
  261. auto HandleInst(FunctionContext& context, SemIR::InstId inst_id, \
  262. SemIR::Name inst) -> void;
  263. #include "toolchain/sem_ir/inst_kind.def"
  264. } // namespace Carbon::Lower
  265. #endif // CARBON_TOOLCHAIN_LOWER_FUNCTION_CONTEXT_H_