1 //===--- ModuleBuilder.cpp - Emit LLVM Code from ASTs ---------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This builds an AST and converts it to LLVM Code.
12 //===----------------------------------------------------------------------===//
14 #include "clang/CodeGen/ModuleBuilder.h"
15 #include "CGDebugInfo.h"
16 #include "CodeGenModule.h"
17 #include "clang/AST/ASTContext.h"
18 #include "clang/AST/DeclObjC.h"
19 #include "clang/AST/Expr.h"
20 #include "clang/Basic/Diagnostic.h"
21 #include "clang/Basic/TargetInfo.h"
22 #include "clang/Frontend/CodeGenOptions.h"
23 #include "llvm/ADT/StringRef.h"
24 #include "llvm/IR/DataLayout.h"
25 #include "llvm/IR/LLVMContext.h"
26 #include "llvm/IR/Module.h"
29 using namespace clang;
30 using namespace CodeGen;
33 class CodeGeneratorImpl : public CodeGenerator {
34 DiagnosticsEngine &Diags;
36 const HeaderSearchOptions &HeaderSearchOpts; // Only used for debug info.
37 const PreprocessorOptions &PreprocessorOpts; // Only used for debug info.
38 const CodeGenOptions CodeGenOpts; // Intentionally copied in.
40 unsigned HandlingTopLevelDecls;
42 /// Use this when emitting decls to block re-entrant decl emission. It will
43 /// emit all deferred decls on scope exit. Set EmitDeferred to false if decl
44 /// emission must be deferred longer, like at the end of a tag definition.
45 struct HandlingTopLevelDeclRAII {
46 CodeGeneratorImpl &Self;
48 HandlingTopLevelDeclRAII(CodeGeneratorImpl &Self,
49 bool EmitDeferred = true)
50 : Self(Self), EmitDeferred(EmitDeferred) {
51 ++Self.HandlingTopLevelDecls;
53 ~HandlingTopLevelDeclRAII() {
54 unsigned Level = --Self.HandlingTopLevelDecls;
55 if (Level == 0 && EmitDeferred)
56 Self.EmitDeferredDecls();
60 CoverageSourceInfo *CoverageInfo;
63 std::unique_ptr<llvm::Module> M;
64 std::unique_ptr<CodeGen::CodeGenModule> Builder;
67 SmallVector<CXXMethodDecl *, 8> DeferredInlineMethodDefinitions;
70 CodeGeneratorImpl(DiagnosticsEngine &diags, llvm::StringRef ModuleName,
71 const HeaderSearchOptions &HSO,
72 const PreprocessorOptions &PPO, const CodeGenOptions &CGO,
74 CoverageSourceInfo *CoverageInfo = nullptr)
75 : Diags(diags), Ctx(nullptr), HeaderSearchOpts(HSO),
76 PreprocessorOpts(PPO), CodeGenOpts(CGO), HandlingTopLevelDecls(0),
77 CoverageInfo(CoverageInfo), M(new llvm::Module(ModuleName, C)) {
78 C.setDiscardValueNames(CGO.DiscardValueNames);
81 ~CodeGeneratorImpl() override {
82 // There should normally not be any leftover inline method definitions.
83 assert(DeferredInlineMethodDefinitions.empty() ||
84 Diags.hasErrorOccurred());
87 CodeGenModule &CGM() {
91 llvm::Module *GetModule() {
95 CGDebugInfo *getCGDebugInfo() {
96 return Builder->getModuleDebugInfo();
99 llvm::Module *ReleaseModule() {
103 const Decl *GetDeclForMangledName(StringRef MangledName) {
105 if (!Builder->lookupRepresentativeDecl(MangledName, Result))
107 const Decl *D = Result.getCanonicalDecl().getDecl();
108 if (auto FD = dyn_cast<FunctionDecl>(D)) {
111 } else if (auto TD = dyn_cast<TagDecl>(D)) {
112 if (auto Def = TD->getDefinition())
118 llvm::Constant *GetAddrOfGlobal(GlobalDecl global, bool isForDefinition) {
119 return Builder->GetAddrOfGlobal(global, ForDefinition_t(isForDefinition));
122 void Initialize(ASTContext &Context) override {
125 M->setTargetTriple(Ctx->getTargetInfo().getTriple().getTriple());
126 M->setDataLayout(Ctx->getTargetInfo().getDataLayout());
127 Builder.reset(new CodeGen::CodeGenModule(Context, HeaderSearchOpts,
128 PreprocessorOpts, CodeGenOpts,
129 *M, Diags, CoverageInfo));
131 for (auto &&Lib : CodeGenOpts.DependentLibraries)
132 Builder->AddDependentLib(Lib);
133 for (auto &&Opt : CodeGenOpts.LinkerOptions)
134 Builder->AppendLinkerOptions(Opt);
137 void HandleCXXStaticMemberVarInstantiation(VarDecl *VD) override {
138 if (Diags.hasErrorOccurred())
141 Builder->HandleCXXStaticMemberVarInstantiation(VD);
144 bool HandleTopLevelDecl(DeclGroupRef DG) override {
145 if (Diags.hasErrorOccurred())
148 HandlingTopLevelDeclRAII HandlingDecl(*this);
150 // Make sure to emit all elements of a Decl.
151 for (DeclGroupRef::iterator I = DG.begin(), E = DG.end(); I != E; ++I)
152 Builder->EmitTopLevelDecl(*I);
157 void EmitDeferredDecls() {
158 if (DeferredInlineMethodDefinitions.empty())
161 // Emit any deferred inline method definitions. Note that more deferred
162 // methods may be added during this loop, since ASTConsumer callbacks
163 // can be invoked if AST inspection results in declarations being added.
164 HandlingTopLevelDeclRAII HandlingDecl(*this);
165 for (unsigned I = 0; I != DeferredInlineMethodDefinitions.size(); ++I)
166 Builder->EmitTopLevelDecl(DeferredInlineMethodDefinitions[I]);
167 DeferredInlineMethodDefinitions.clear();
170 void HandleInlineFunctionDefinition(FunctionDecl *D) override {
171 if (Diags.hasErrorOccurred())
174 assert(D->doesThisDeclarationHaveABody());
176 // Handle friend functions.
177 if (D->isInIdentifierNamespace(Decl::IDNS_OrdinaryFriend)) {
178 if (Ctx->getTargetInfo().getCXXABI().isMicrosoft()
179 && !D->getLexicalDeclContext()->isDependentContext())
180 Builder->EmitTopLevelDecl(D);
184 // Otherwise, must be a method.
185 auto MD = cast<CXXMethodDecl>(D);
187 // We may want to emit this definition. However, that decision might be
188 // based on computing the linkage, and we have to defer that in case we
189 // are inside of something that will change the method's final linkage,
193 // void foo() { bar(); }
195 DeferredInlineMethodDefinitions.push_back(MD);
197 // Provide some coverage mapping even for methods that aren't emitted.
198 // Don't do this for templated classes though, as they may not be
200 if (!MD->getParent()->isDependentContext())
201 Builder->AddDeferredUnusedCoverageMapping(MD);
204 /// HandleTagDeclDefinition - This callback is invoked each time a TagDecl
205 /// to (e.g. struct, union, enum, class) is completed. This allows the
206 /// client hack on the type, which can occur at any point in the file
207 /// (because these can be defined in declspecs).
208 void HandleTagDeclDefinition(TagDecl *D) override {
209 if (Diags.hasErrorOccurred())
212 // Don't allow re-entrant calls to CodeGen triggered by PCH
213 // deserialization to emit deferred decls.
214 HandlingTopLevelDeclRAII HandlingDecl(*this, /*EmitDeferred=*/false);
216 Builder->UpdateCompletedType(D);
218 // For MSVC compatibility, treat declarations of static data members with
219 // inline initializers as definitions.
220 if (Ctx->getTargetInfo().getCXXABI().isMicrosoft()) {
221 for (Decl *Member : D->decls()) {
222 if (VarDecl *VD = dyn_cast<VarDecl>(Member)) {
223 if (Ctx->isMSStaticDataMemberInlineDefinition(VD) &&
224 Ctx->DeclMustBeEmitted(VD)) {
225 Builder->EmitGlobal(VD);
230 // For OpenMP emit declare reduction functions, if required.
231 if (Ctx->getLangOpts().OpenMP) {
232 for (Decl *Member : D->decls()) {
233 if (auto *DRD = dyn_cast<OMPDeclareReductionDecl>(Member)) {
234 if (Ctx->DeclMustBeEmitted(DRD))
235 Builder->EmitGlobal(DRD);
241 void HandleTagDeclRequiredDefinition(const TagDecl *D) override {
242 if (Diags.hasErrorOccurred())
245 // Don't allow re-entrant calls to CodeGen triggered by PCH
246 // deserialization to emit deferred decls.
247 HandlingTopLevelDeclRAII HandlingDecl(*this, /*EmitDeferred=*/false);
249 if (CodeGen::CGDebugInfo *DI = Builder->getModuleDebugInfo())
250 if (const RecordDecl *RD = dyn_cast<RecordDecl>(D))
251 DI->completeRequiredType(RD);
254 void HandleTranslationUnit(ASTContext &Ctx) override {
255 // Release the Builder when there is no error.
256 if (!Diags.hasErrorOccurred() && Builder)
259 // If there are errors before or when releasing the Builder, reset
260 // the module to stop here before invoking the backend.
261 if (Diags.hasErrorOccurred()) {
269 void AssignInheritanceModel(CXXRecordDecl *RD) override {
270 if (Diags.hasErrorOccurred())
273 Builder->RefreshTypeCacheForClass(RD);
276 void CompleteTentativeDefinition(VarDecl *D) override {
277 if (Diags.hasErrorOccurred())
280 Builder->EmitTentativeDefinition(D);
283 void HandleVTable(CXXRecordDecl *RD) override {
284 if (Diags.hasErrorOccurred())
287 Builder->EmitVTable(RD);
292 void CodeGenerator::anchor() { }
294 CodeGenModule &CodeGenerator::CGM() {
295 return static_cast<CodeGeneratorImpl*>(this)->CGM();
298 llvm::Module *CodeGenerator::GetModule() {
299 return static_cast<CodeGeneratorImpl*>(this)->GetModule();
302 llvm::Module *CodeGenerator::ReleaseModule() {
303 return static_cast<CodeGeneratorImpl*>(this)->ReleaseModule();
306 CGDebugInfo *CodeGenerator::getCGDebugInfo() {
307 return static_cast<CodeGeneratorImpl*>(this)->getCGDebugInfo();
310 const Decl *CodeGenerator::GetDeclForMangledName(llvm::StringRef name) {
311 return static_cast<CodeGeneratorImpl*>(this)->GetDeclForMangledName(name);
314 llvm::Constant *CodeGenerator::GetAddrOfGlobal(GlobalDecl global,
315 bool isForDefinition) {
316 return static_cast<CodeGeneratorImpl*>(this)
317 ->GetAddrOfGlobal(global, isForDefinition);
320 CodeGenerator *clang::CreateLLVMCodeGen(
321 DiagnosticsEngine &Diags, llvm::StringRef ModuleName,
322 const HeaderSearchOptions &HeaderSearchOpts,
323 const PreprocessorOptions &PreprocessorOpts, const CodeGenOptions &CGO,
324 llvm::LLVMContext &C, CoverageSourceInfo *CoverageInfo) {
325 return new CodeGeneratorImpl(Diags, ModuleName, HeaderSearchOpts,
326 PreprocessorOpts, CGO, C, CoverageInfo);