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 llvm::Module *ReleaseModule() {
99 const Decl *GetDeclForMangledName(StringRef MangledName) {
101 if (!Builder->lookupRepresentativeDecl(MangledName, Result))
103 const Decl *D = Result.getCanonicalDecl().getDecl();
104 if (auto FD = dyn_cast<FunctionDecl>(D)) {
107 } else if (auto TD = dyn_cast<TagDecl>(D)) {
108 if (auto Def = TD->getDefinition())
114 llvm::Constant *GetAddrOfGlobal(GlobalDecl global, bool isForDefinition) {
115 return Builder->GetAddrOfGlobal(global, ForDefinition_t(isForDefinition));
118 void Initialize(ASTContext &Context) override {
121 M->setTargetTriple(Ctx->getTargetInfo().getTriple().getTriple());
122 M->setDataLayout(Ctx->getTargetInfo().getDataLayout());
123 Builder.reset(new CodeGen::CodeGenModule(Context, HeaderSearchOpts,
124 PreprocessorOpts, CodeGenOpts,
125 *M, Diags, CoverageInfo));
127 for (auto &&Lib : CodeGenOpts.DependentLibraries)
128 Builder->AddDependentLib(Lib);
129 for (auto &&Opt : CodeGenOpts.LinkerOptions)
130 Builder->AppendLinkerOptions(Opt);
133 void HandleCXXStaticMemberVarInstantiation(VarDecl *VD) override {
134 if (Diags.hasErrorOccurred())
137 Builder->HandleCXXStaticMemberVarInstantiation(VD);
140 bool HandleTopLevelDecl(DeclGroupRef DG) override {
141 if (Diags.hasErrorOccurred())
144 HandlingTopLevelDeclRAII HandlingDecl(*this);
146 // Make sure to emit all elements of a Decl.
147 for (DeclGroupRef::iterator I = DG.begin(), E = DG.end(); I != E; ++I)
148 Builder->EmitTopLevelDecl(*I);
153 void EmitDeferredDecls() {
154 if (DeferredInlineMethodDefinitions.empty())
157 // Emit any deferred inline method definitions. Note that more deferred
158 // methods may be added during this loop, since ASTConsumer callbacks
159 // can be invoked if AST inspection results in declarations being added.
160 HandlingTopLevelDeclRAII HandlingDecl(*this);
161 for (unsigned I = 0; I != DeferredInlineMethodDefinitions.size(); ++I)
162 Builder->EmitTopLevelDecl(DeferredInlineMethodDefinitions[I]);
163 DeferredInlineMethodDefinitions.clear();
166 void HandleInlineFunctionDefinition(FunctionDecl *D) override {
167 if (Diags.hasErrorOccurred())
170 assert(D->doesThisDeclarationHaveABody());
172 // Handle friend functions.
173 if (D->isInIdentifierNamespace(Decl::IDNS_OrdinaryFriend)) {
174 if (Ctx->getTargetInfo().getCXXABI().isMicrosoft()
175 && !D->getLexicalDeclContext()->isDependentContext())
176 Builder->EmitTopLevelDecl(D);
180 // Otherwise, must be a method.
181 auto MD = cast<CXXMethodDecl>(D);
183 // We may want to emit this definition. However, that decision might be
184 // based on computing the linkage, and we have to defer that in case we
185 // are inside of something that will change the method's final linkage,
189 // void foo() { bar(); }
191 DeferredInlineMethodDefinitions.push_back(MD);
193 // Provide some coverage mapping even for methods that aren't emitted.
194 // Don't do this for templated classes though, as they may not be
196 if (!MD->getParent()->getDescribedClassTemplate())
197 Builder->AddDeferredUnusedCoverageMapping(MD);
200 /// HandleTagDeclDefinition - This callback is invoked each time a TagDecl
201 /// to (e.g. struct, union, enum, class) is completed. This allows the
202 /// client hack on the type, which can occur at any point in the file
203 /// (because these can be defined in declspecs).
204 void HandleTagDeclDefinition(TagDecl *D) override {
205 if (Diags.hasErrorOccurred())
208 // Don't allow re-entrant calls to CodeGen triggered by PCH
209 // deserialization to emit deferred decls.
210 HandlingTopLevelDeclRAII HandlingDecl(*this, /*EmitDeferred=*/false);
212 Builder->UpdateCompletedType(D);
214 // For MSVC compatibility, treat declarations of static data members with
215 // inline initializers as definitions.
216 if (Ctx->getTargetInfo().getCXXABI().isMicrosoft()) {
217 for (Decl *Member : D->decls()) {
218 if (VarDecl *VD = dyn_cast<VarDecl>(Member)) {
219 if (Ctx->isMSStaticDataMemberInlineDefinition(VD) &&
220 Ctx->DeclMustBeEmitted(VD)) {
221 Builder->EmitGlobal(VD);
226 // For OpenMP emit declare reduction functions, if required.
227 if (Ctx->getLangOpts().OpenMP) {
228 for (Decl *Member : D->decls()) {
229 if (auto *DRD = dyn_cast<OMPDeclareReductionDecl>(Member)) {
230 if (Ctx->DeclMustBeEmitted(DRD))
231 Builder->EmitGlobal(DRD);
237 void HandleTagDeclRequiredDefinition(const TagDecl *D) override {
238 if (Diags.hasErrorOccurred())
241 // Don't allow re-entrant calls to CodeGen triggered by PCH
242 // deserialization to emit deferred decls.
243 HandlingTopLevelDeclRAII HandlingDecl(*this, /*EmitDeferred=*/false);
245 if (CodeGen::CGDebugInfo *DI = Builder->getModuleDebugInfo())
246 if (const RecordDecl *RD = dyn_cast<RecordDecl>(D))
247 DI->completeRequiredType(RD);
250 void HandleTranslationUnit(ASTContext &Ctx) override {
251 // Release the Builder when there is no error.
252 if (!Diags.hasErrorOccurred() && Builder)
255 // If there are errors before or when releasing the Builder, reset
256 // the module to stop here before invoking the backend.
257 if (Diags.hasErrorOccurred()) {
265 void AssignInheritanceModel(CXXRecordDecl *RD) override {
266 if (Diags.hasErrorOccurred())
269 Builder->RefreshTypeCacheForClass(RD);
272 void CompleteTentativeDefinition(VarDecl *D) override {
273 if (Diags.hasErrorOccurred())
276 Builder->EmitTentativeDefinition(D);
279 void HandleVTable(CXXRecordDecl *RD) override {
280 if (Diags.hasErrorOccurred())
283 Builder->EmitVTable(RD);
288 void CodeGenerator::anchor() { }
290 CodeGenModule &CodeGenerator::CGM() {
291 return static_cast<CodeGeneratorImpl*>(this)->CGM();
294 llvm::Module *CodeGenerator::GetModule() {
295 return static_cast<CodeGeneratorImpl*>(this)->GetModule();
298 llvm::Module *CodeGenerator::ReleaseModule() {
299 return static_cast<CodeGeneratorImpl*>(this)->ReleaseModule();
302 const Decl *CodeGenerator::GetDeclForMangledName(llvm::StringRef name) {
303 return static_cast<CodeGeneratorImpl*>(this)->GetDeclForMangledName(name);
306 llvm::Constant *CodeGenerator::GetAddrOfGlobal(GlobalDecl global,
307 bool isForDefinition) {
308 return static_cast<CodeGeneratorImpl*>(this)
309 ->GetAddrOfGlobal(global, isForDefinition);
312 CodeGenerator *clang::CreateLLVMCodeGen(
313 DiagnosticsEngine &Diags, llvm::StringRef ModuleName,
314 const HeaderSearchOptions &HeaderSearchOpts,
315 const PreprocessorOptions &PreprocessorOpts, const CodeGenOptions &CGO,
316 llvm::LLVMContext &C, CoverageSourceInfo *CoverageInfo) {
317 return new CodeGeneratorImpl(Diags, ModuleName, HeaderSearchOpts,
318 PreprocessorOpts, CGO, C, CoverageInfo);