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"
28 using namespace clang;
31 class CodeGeneratorImpl : public CodeGenerator {
32 DiagnosticsEngine &Diags;
34 const HeaderSearchOptions &HeaderSearchOpts; // Only used for debug info.
35 const PreprocessorOptions &PreprocessorOpts; // Only used for debug info.
36 const CodeGenOptions CodeGenOpts; // Intentionally copied in.
38 unsigned HandlingTopLevelDecls;
39 struct HandlingTopLevelDeclRAII {
40 CodeGeneratorImpl &Self;
41 HandlingTopLevelDeclRAII(CodeGeneratorImpl &Self) : Self(Self) {
42 ++Self.HandlingTopLevelDecls;
44 ~HandlingTopLevelDeclRAII() {
45 if (--Self.HandlingTopLevelDecls == 0)
46 Self.EmitDeferredDecls();
50 CoverageSourceInfo *CoverageInfo;
53 std::unique_ptr<llvm::Module> M;
54 std::unique_ptr<CodeGen::CodeGenModule> Builder;
57 SmallVector<CXXMethodDecl *, 8> DeferredInlineMethodDefinitions;
60 CodeGeneratorImpl(DiagnosticsEngine &diags, const std::string &ModuleName,
61 const HeaderSearchOptions &HSO,
62 const PreprocessorOptions &PPO, const CodeGenOptions &CGO,
64 CoverageSourceInfo *CoverageInfo = nullptr)
65 : Diags(diags), Ctx(nullptr), HeaderSearchOpts(HSO),
66 PreprocessorOpts(PPO), CodeGenOpts(CGO), HandlingTopLevelDecls(0),
67 CoverageInfo(CoverageInfo),
68 M(new llvm::Module(ModuleName, C)) {}
70 ~CodeGeneratorImpl() override {
71 // There should normally not be any leftover inline method definitions.
72 assert(DeferredInlineMethodDefinitions.empty() ||
73 Diags.hasErrorOccurred());
76 llvm::Module* GetModule() override {
80 const Decl *GetDeclForMangledName(StringRef MangledName) override {
82 if (!Builder->lookupRepresentativeDecl(MangledName, Result))
84 const Decl *D = Result.getCanonicalDecl().getDecl();
85 if (auto FD = dyn_cast<FunctionDecl>(D)) {
88 } else if (auto TD = dyn_cast<TagDecl>(D)) {
89 if (auto Def = TD->getDefinition())
95 llvm::Module *ReleaseModule() override { return M.release(); }
97 void Initialize(ASTContext &Context) override {
100 M->setTargetTriple(Ctx->getTargetInfo().getTriple().getTriple());
101 M->setDataLayout(Ctx->getTargetInfo().getDataLayoutString());
102 Builder.reset(new CodeGen::CodeGenModule(Context, HeaderSearchOpts,
103 PreprocessorOpts, CodeGenOpts,
104 *M, Diags, CoverageInfo));
106 for (auto &&Lib : CodeGenOpts.DependentLibraries)
107 HandleDependentLibrary(Lib);
108 for (auto &&Opt : CodeGenOpts.LinkerOptions)
109 HandleLinkerOption(Opt);
112 void HandleCXXStaticMemberVarInstantiation(VarDecl *VD) override {
113 if (Diags.hasErrorOccurred())
116 Builder->HandleCXXStaticMemberVarInstantiation(VD);
119 bool HandleTopLevelDecl(DeclGroupRef DG) override {
120 if (Diags.hasErrorOccurred())
123 HandlingTopLevelDeclRAII HandlingDecl(*this);
125 // Make sure to emit all elements of a Decl.
126 for (DeclGroupRef::iterator I = DG.begin(), E = DG.end(); I != E; ++I)
127 Builder->EmitTopLevelDecl(*I);
132 void EmitDeferredDecls() {
133 if (DeferredInlineMethodDefinitions.empty())
136 // Emit any deferred inline method definitions. Note that more deferred
137 // methods may be added during this loop, since ASTConsumer callbacks
138 // can be invoked if AST inspection results in declarations being added.
139 HandlingTopLevelDeclRAII HandlingDecl(*this);
140 for (unsigned I = 0; I != DeferredInlineMethodDefinitions.size(); ++I)
141 Builder->EmitTopLevelDecl(DeferredInlineMethodDefinitions[I]);
142 DeferredInlineMethodDefinitions.clear();
145 void HandleInlineMethodDefinition(CXXMethodDecl *D) override {
146 if (Diags.hasErrorOccurred())
149 assert(D->doesThisDeclarationHaveABody());
151 // We may want to emit this definition. However, that decision might be
152 // based on computing the linkage, and we have to defer that in case we
153 // are inside of something that will change the method's final linkage,
157 // void foo() { bar(); }
159 DeferredInlineMethodDefinitions.push_back(D);
161 // Provide some coverage mapping even for methods that aren't emitted.
162 // Don't do this for templated classes though, as they may not be
164 if (!D->getParent()->getDescribedClassTemplate())
165 Builder->AddDeferredUnusedCoverageMapping(D);
168 /// HandleTagDeclDefinition - This callback is invoked each time a TagDecl
169 /// to (e.g. struct, union, enum, class) is completed. This allows the
170 /// client hack on the type, which can occur at any point in the file
171 /// (because these can be defined in declspecs).
172 void HandleTagDeclDefinition(TagDecl *D) override {
173 if (Diags.hasErrorOccurred())
176 Builder->UpdateCompletedType(D);
178 // For MSVC compatibility, treat declarations of static data members with
179 // inline initializers as definitions.
180 if (Ctx->getTargetInfo().getCXXABI().isMicrosoft()) {
181 for (Decl *Member : D->decls()) {
182 if (VarDecl *VD = dyn_cast<VarDecl>(Member)) {
183 if (Ctx->isMSStaticDataMemberInlineDefinition(VD) &&
184 Ctx->DeclMustBeEmitted(VD)) {
185 Builder->EmitGlobal(VD);
192 void HandleTagDeclRequiredDefinition(const TagDecl *D) override {
193 if (Diags.hasErrorOccurred())
196 if (CodeGen::CGDebugInfo *DI = Builder->getModuleDebugInfo())
197 if (const RecordDecl *RD = dyn_cast<RecordDecl>(D))
198 DI->completeRequiredType(RD);
201 void HandleTranslationUnit(ASTContext &Ctx) override {
202 // Release the Builder when there is no error.
203 if (!Diags.hasErrorOccurred() && Builder)
206 // If there are errors before or when releasing the Builder, reset
207 // the module to stop here before invoking the backend.
208 if (Diags.hasErrorOccurred()) {
216 void AssignInheritanceModel(CXXRecordDecl *RD) override {
217 if (Diags.hasErrorOccurred())
220 Builder->RefreshTypeCacheForClass(RD);
223 void CompleteTentativeDefinition(VarDecl *D) override {
224 if (Diags.hasErrorOccurred())
227 Builder->EmitTentativeDefinition(D);
230 void HandleVTable(CXXRecordDecl *RD) override {
231 if (Diags.hasErrorOccurred())
234 Builder->EmitVTable(RD);
237 void HandleLinkerOption(llvm::StringRef Opts) override {
238 Builder->AppendLinkerOptions(Opts);
241 void HandleDetectMismatch(llvm::StringRef Name,
242 llvm::StringRef Value) override {
243 Builder->AddDetectMismatch(Name, Value);
246 void HandleDependentLibrary(llvm::StringRef Lib) override {
247 Builder->AddDependentLib(Lib);
252 void CodeGenerator::anchor() { }
254 CodeGenerator *clang::CreateLLVMCodeGen(
255 DiagnosticsEngine &Diags, const std::string &ModuleName,
256 const HeaderSearchOptions &HeaderSearchOpts,
257 const PreprocessorOptions &PreprocessorOpts, const CodeGenOptions &CGO,
258 llvm::LLVMContext &C, CoverageSourceInfo *CoverageInfo) {
259 return new CodeGeneratorImpl(Diags, ModuleName, HeaderSearchOpts,
260 PreprocessorOpts, CGO, C, CoverageInfo);