blob: 511cf75d6aa645400a4c172d4620b6b958c631cc [file] [log] [blame]
Chris Lattnerf97fe382007-05-24 06:29:05 +00001//===--- ModuleBuilder.cpp - Emit LLVM Code from ASTs ---------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner5b12ab82007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattnerf97fe382007-05-24 06:29:05 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This builds an AST and converts it to LLVM Code.
11//
12//===----------------------------------------------------------------------===//
13
14#include "clang/CodeGen/ModuleBuilder.h"
David Blaikie48ad6dc2013-07-13 21:08:14 +000015#include "CGDebugInfo.h"
Chandler Carruth5553d0d2014-01-07 11:51:46 +000016#include "CodeGenModule.h"
Chris Lattneradf1f512008-02-06 02:01:47 +000017#include "clang/AST/ASTContext.h"
Daniel Dunbar221fa942008-08-11 04:54:23 +000018#include "clang/AST/DeclObjC.h"
19#include "clang/AST/Expr.h"
Chris Lattneradf1f512008-02-06 02:01:47 +000020#include "clang/Basic/Diagnostic.h"
21#include "clang/Basic/TargetInfo.h"
Saleem Abdulrasool10a49722016-04-08 16:52:00 +000022#include "clang/Frontend/CodeGenOptions.h"
Reid Klecknere43f0fe2013-05-08 13:44:39 +000023#include "llvm/ADT/StringRef.h"
Chandler Carruthffd55512013-01-02 11:45:17 +000024#include "llvm/IR/DataLayout.h"
25#include "llvm/IR/LLVMContext.h"
26#include "llvm/IR/Module.h"
Ahmed Charlesdfca6f92014-03-09 11:36:40 +000027#include <memory>
John McCall6909fee2016-05-18 05:21:18 +000028
Chris Lattner984fac52009-03-26 05:00:52 +000029using namespace clang;
John McCall6909fee2016-05-18 05:21:18 +000030using namespace CodeGen;
Ted Kremenek2c674f62008-08-05 18:50:11 +000031
Chris Lattneradf1f512008-02-06 02:01:47 +000032namespace {
Benjamin Kramer337e3a52009-11-28 19:45:26 +000033 class CodeGeneratorImpl : public CodeGenerator {
David Blaikie9c902b52011-09-25 23:23:43 +000034 DiagnosticsEngine &Diags;
Chris Lattneradf1f512008-02-06 02:01:47 +000035 ASTContext *Ctx;
Adrian Prantle74f5252015-06-30 02:26:03 +000036 const HeaderSearchOptions &HeaderSearchOpts; // Only used for debug info.
37 const PreprocessorOptions &PreprocessorOpts; // Only used for debug info.
Chandler Carruthbc55fe22009-11-12 17:24:48 +000038 const CodeGenOptions CodeGenOpts; // Intentionally copied in.
Richard Smith7f5755c2014-08-01 22:42:16 +000039
40 unsigned HandlingTopLevelDecls;
Reid Klecknerea53dba2016-04-22 18:46:33 +000041
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.
Richard Smith7f5755c2014-08-01 22:42:16 +000045 struct HandlingTopLevelDeclRAII {
46 CodeGeneratorImpl &Self;
Reid Klecknerea53dba2016-04-22 18:46:33 +000047 bool EmitDeferred;
48 HandlingTopLevelDeclRAII(CodeGeneratorImpl &Self,
49 bool EmitDeferred = true)
50 : Self(Self), EmitDeferred(EmitDeferred) {
Richard Smith7f5755c2014-08-01 22:42:16 +000051 ++Self.HandlingTopLevelDecls;
52 }
53 ~HandlingTopLevelDeclRAII() {
Reid Klecknerea53dba2016-04-22 18:46:33 +000054 unsigned Level = --Self.HandlingTopLevelDecls;
55 if (Level == 0 && EmitDeferred)
Richard Smith7f5755c2014-08-01 22:42:16 +000056 Self.EmitDeferredDecls();
57 }
58 };
59
Alex Lorenzee024992014-08-04 18:41:51 +000060 CoverageSourceInfo *CoverageInfo;
61
Chris Lattneradf1f512008-02-06 02:01:47 +000062 protected:
Ahmed Charlesb8984322014-03-07 20:03:18 +000063 std::unique_ptr<llvm::Module> M;
64 std::unique_ptr<CodeGen::CodeGenModule> Builder;
65
Hans Wennborg2b0d0142014-12-18 19:19:00 +000066 private:
Reid Kleckner78381c62018-09-18 23:16:30 +000067 SmallVector<FunctionDecl *, 8> DeferredInlineMemberFuncDefs;
Hans Wennborg2b0d0142014-12-18 19:19:00 +000068
Chris Lattneradf1f512008-02-06 02:01:47 +000069 public:
John McCall6909fee2016-05-18 05:21:18 +000070 CodeGeneratorImpl(DiagnosticsEngine &diags, llvm::StringRef ModuleName,
Adrian Prantle74f5252015-06-30 02:26:03 +000071 const HeaderSearchOptions &HSO,
72 const PreprocessorOptions &PPO, const CodeGenOptions &CGO,
73 llvm::LLVMContext &C,
Alex Lorenzee024992014-08-04 18:41:51 +000074 CoverageSourceInfo *CoverageInfo = nullptr)
Adrian Prantle74f5252015-06-30 02:26:03 +000075 : Diags(diags), Ctx(nullptr), HeaderSearchOpts(HSO),
76 PreprocessorOpts(PPO), CodeGenOpts(CGO), HandlingTopLevelDecls(0),
Mehdi Amini557c20a2016-03-13 21:05:23 +000077 CoverageInfo(CoverageInfo), M(new llvm::Module(ModuleName, C)) {
78 C.setDiscardValueNames(CGO.DiscardValueNames);
79 }
Mike Stump11289f42009-09-09 15:08:12 +000080
Alexander Kornienko34eb2072015-04-11 02:00:23 +000081 ~CodeGeneratorImpl() override {
Hans Wennborg0c0a8c82014-12-19 23:35:11 +000082 // There should normally not be any leftover inline method definitions.
Reid Kleckner78381c62018-09-18 23:16:30 +000083 assert(DeferredInlineMemberFuncDefs.empty() ||
Hans Wennborg0c0a8c82014-12-19 23:35:11 +000084 Diags.hasErrorOccurred());
Hans Wennborg2b0d0142014-12-18 19:19:00 +000085 }
Mike Stump11289f42009-09-09 15:08:12 +000086
John McCall6909fee2016-05-18 05:21:18 +000087 CodeGenModule &CGM() {
88 return *Builder;
89 }
90
91 llvm::Module *GetModule() {
Daniel Dunbar30c514e2008-10-21 19:55:09 +000092 return M.get();
93 }
Mike Stump11289f42009-09-09 15:08:12 +000094
Amjad Aboud546bc112017-02-09 22:07:24 +000095 CGDebugInfo *getCGDebugInfo() {
96 return Builder->getModuleDebugInfo();
97 }
98
John McCall6909fee2016-05-18 05:21:18 +000099 llvm::Module *ReleaseModule() {
100 return M.release();
101 }
102
103 const Decl *GetDeclForMangledName(StringRef MangledName) {
Alp Tokerfb8d02b2014-06-05 22:10:59 +0000104 GlobalDecl Result;
105 if (!Builder->lookupRepresentativeDecl(MangledName, Result))
106 return nullptr;
107 const Decl *D = Result.getCanonicalDecl().getDecl();
108 if (auto FD = dyn_cast<FunctionDecl>(D)) {
109 if (FD->hasBody(FD))
110 return FD;
111 } else if (auto TD = dyn_cast<TagDecl>(D)) {
112 if (auto Def = TD->getDefinition())
113 return Def;
114 }
115 return D;
116 }
117
John McCall6909fee2016-05-18 05:21:18 +0000118 llvm::Constant *GetAddrOfGlobal(GlobalDecl global, bool isForDefinition) {
John McCalld195d4c2016-11-30 23:25:13 +0000119 return Builder->GetAddrOfGlobal(global, ForDefinition_t(isForDefinition));
John McCall6909fee2016-05-18 05:21:18 +0000120 }
Mike Stump11289f42009-09-09 15:08:12 +0000121
Vassil Vassilev4d54e5432017-08-27 10:58:03 +0000122 llvm::Module *StartModule(llvm::StringRef ModuleName,
123 llvm::LLVMContext &C) {
124 assert(!M && "Replacing existing Module?");
125 M.reset(new llvm::Module(ModuleName, C));
126 Initialize(*Ctx);
127 return M.get();
128 }
129
Craig Topper4f12f102014-03-12 06:41:41 +0000130 void Initialize(ASTContext &Context) override {
Chris Lattneradf1f512008-02-06 02:01:47 +0000131 Ctx = &Context;
Mike Stump11289f42009-09-09 15:08:12 +0000132
Douglas Gregore8bbc122011-09-02 00:18:52 +0000133 M->setTargetTriple(Ctx->getTargetInfo().getTriple().getTriple());
James Y Knightb214cbc2016-03-04 19:00:41 +0000134 M->setDataLayout(Ctx->getTargetInfo().getDataLayout());
Mehdi Aminica3cf9e2015-07-24 16:04:29 +0000135 Builder.reset(new CodeGen::CodeGenModule(Context, HeaderSearchOpts,
136 PreprocessorOpts, CodeGenOpts,
137 *M, Diags, CoverageInfo));
Hans Wennborg75958c42013-08-08 00:17:41 +0000138
Peter Collingbournedc134532016-01-16 00:31:22 +0000139 for (auto &&Lib : CodeGenOpts.DependentLibraries)
Nico Weber66220292016-03-02 17:28:48 +0000140 Builder->AddDependentLib(Lib);
Peter Collingbournedc134532016-01-16 00:31:22 +0000141 for (auto &&Opt : CodeGenOpts.LinkerOptions)
Nico Weber66220292016-03-02 17:28:48 +0000142 Builder->AppendLinkerOptions(Opt);
Chris Lattneradf1f512008-02-06 02:01:47 +0000143 }
Mike Stump11289f42009-09-09 15:08:12 +0000144
Craig Topper4f12f102014-03-12 06:41:41 +0000145 void HandleCXXStaticMemberVarInstantiation(VarDecl *VD) override {
David Blaikie4a9ec7b2013-08-19 21:02:26 +0000146 if (Diags.hasErrorOccurred())
147 return;
148
Rafael Espindoladf88f6f2012-03-08 15:51:03 +0000149 Builder->HandleCXXStaticMemberVarInstantiation(VD);
Rafael Espindola189fa742012-03-05 10:54:55 +0000150 }
151
Craig Topper4f12f102014-03-12 06:41:41 +0000152 bool HandleTopLevelDecl(DeclGroupRef DG) override {
David Blaikie4a9ec7b2013-08-19 21:02:26 +0000153 if (Diags.hasErrorOccurred())
154 return true;
155
Richard Smith7f5755c2014-08-01 22:42:16 +0000156 HandlingTopLevelDeclRAII HandlingDecl(*this);
157
Douglas Gregor6e6ad602009-01-20 01:17:11 +0000158 // Make sure to emit all elements of a Decl.
Chris Lattner5bbb3c82009-03-29 16:50:03 +0000159 for (DeclGroupRef::iterator I = DG.begin(), E = DG.end(); I != E; ++I)
160 Builder->EmitTopLevelDecl(*I);
Hans Wennborgdfcb7d62014-06-06 17:36:17 +0000161
Richard Smith7f5755c2014-08-01 22:42:16 +0000162 return true;
163 }
164
165 void EmitDeferredDecls() {
Reid Kleckner78381c62018-09-18 23:16:30 +0000166 if (DeferredInlineMemberFuncDefs.empty())
Richard Smithc9cbde72014-08-13 21:15:09 +0000167 return;
168
Richard Smith1ba0a072014-08-01 20:39:36 +0000169 // Emit any deferred inline method definitions. Note that more deferred
170 // methods may be added during this loop, since ASTConsumer callbacks
171 // can be invoked if AST inspection results in declarations being added.
Richard Smithc9cbde72014-08-13 21:15:09 +0000172 HandlingTopLevelDeclRAII HandlingDecl(*this);
Reid Kleckner78381c62018-09-18 23:16:30 +0000173 for (unsigned I = 0; I != DeferredInlineMemberFuncDefs.size(); ++I)
174 Builder->EmitTopLevelDecl(DeferredInlineMemberFuncDefs[I]);
175 DeferredInlineMemberFuncDefs.clear();
Chris Lattneradf1f512008-02-06 02:01:47 +0000176 }
Daniel Dunbarfce4be82008-08-15 23:26:23 +0000177
Stephan Bergmann17d7d142016-03-30 06:27:31 +0000178 void HandleInlineFunctionDefinition(FunctionDecl *D) override {
Hans Wennborga926d842014-05-23 20:37:38 +0000179 if (Diags.hasErrorOccurred())
180 return;
181
182 assert(D->doesThisDeclarationHaveABody());
183
Hans Wennborgdfcb7d62014-06-06 17:36:17 +0000184 // We may want to emit this definition. However, that decision might be
185 // based on computing the linkage, and we have to defer that in case we
186 // are inside of something that will change the method's final linkage,
187 // e.g.
188 // typedef struct {
189 // void bar();
190 // void foo() { bar(); }
191 // } A;
Reid Kleckner78381c62018-09-18 23:16:30 +0000192 DeferredInlineMemberFuncDefs.push_back(D);
Alex Lorenzee024992014-08-04 18:41:51 +0000193
Justin Bogner94d384e2014-11-18 00:34:46 +0000194 // Provide some coverage mapping even for methods that aren't emitted.
195 // Don't do this for templated classes though, as they may not be
196 // instantiable.
Reid Kleckner78381c62018-09-18 23:16:30 +0000197 if (!D->getLexicalDeclContext()->isDependentContext())
198 Builder->AddDeferredUnusedCoverageMapping(D);
Hans Wennborga926d842014-05-23 20:37:38 +0000199 }
200
Chris Lattnera5e4d302008-02-06 04:51:19 +0000201 /// HandleTagDeclDefinition - This callback is invoked each time a TagDecl
Chris Lattner5bbb3c82009-03-29 16:50:03 +0000202 /// to (e.g. struct, union, enum, class) is completed. This allows the
203 /// client hack on the type, which can occur at any point in the file
204 /// (because these can be defined in declspecs).
Craig Topper4f12f102014-03-12 06:41:41 +0000205 void HandleTagDeclDefinition(TagDecl *D) override {
David Blaikie4a9ec7b2013-08-19 21:02:26 +0000206 if (Diags.hasErrorOccurred())
207 return;
208
Reid Klecknerea53dba2016-04-22 18:46:33 +0000209 // Don't allow re-entrant calls to CodeGen triggered by PCH
210 // deserialization to emit deferred decls.
211 HandlingTopLevelDeclRAII HandlingDecl(*this, /*EmitDeferred=*/false);
212
Chris Lattner68be6062008-02-06 05:08:19 +0000213 Builder->UpdateCompletedType(D);
Hans Wennborg56fc62b2014-07-17 20:25:23 +0000214
215 // For MSVC compatibility, treat declarations of static data members with
216 // inline initializers as definitions.
David Majnemer3f021502015-10-08 04:53:31 +0000217 if (Ctx->getTargetInfo().getCXXABI().isMicrosoft()) {
Hans Wennborg56fc62b2014-07-17 20:25:23 +0000218 for (Decl *Member : D->decls()) {
219 if (VarDecl *VD = dyn_cast<VarDecl>(Member)) {
220 if (Ctx->isMSStaticDataMemberInlineDefinition(VD) &&
221 Ctx->DeclMustBeEmitted(VD)) {
222 Builder->EmitGlobal(VD);
223 }
224 }
225 }
226 }
Alexey Bataevc5b1d322016-03-04 09:22:22 +0000227 // For OpenMP emit declare reduction functions, if required.
228 if (Ctx->getLangOpts().OpenMP) {
229 for (Decl *Member : D->decls()) {
230 if (auto *DRD = dyn_cast<OMPDeclareReductionDecl>(Member)) {
231 if (Ctx->DeclMustBeEmitted(DRD))
232 Builder->EmitGlobal(DRD);
233 }
234 }
235 }
Chris Lattnera5e4d302008-02-06 04:51:19 +0000236 }
Ted Kremenek7db4f602008-08-07 19:47:41 +0000237
Craig Topper4f12f102014-03-12 06:41:41 +0000238 void HandleTagDeclRequiredDefinition(const TagDecl *D) override {
David Blaikie4a9ec7b2013-08-19 21:02:26 +0000239 if (Diags.hasErrorOccurred())
240 return;
241
Reid Klecknerea53dba2016-04-22 18:46:33 +0000242 // Don't allow re-entrant calls to CodeGen triggered by PCH
243 // deserialization to emit deferred decls.
244 HandlingTopLevelDeclRAII HandlingDecl(*this, /*EmitDeferred=*/false);
245
David Blaikie48ad6dc2013-07-13 21:08:14 +0000246 if (CodeGen::CGDebugInfo *DI = Builder->getModuleDebugInfo())
247 if (const RecordDecl *RD = dyn_cast<RecordDecl>(D))
David Blaikieb2e86eb2013-08-15 20:49:17 +0000248 DI->completeRequiredType(RD);
David Blaikie48ad6dc2013-07-13 21:08:14 +0000249 }
250
Craig Topper4f12f102014-03-12 06:41:41 +0000251 void HandleTranslationUnit(ASTContext &Ctx) override {
Manman Ren581c2b92016-01-28 23:29:02 +0000252 // Release the Builder when there is no error.
253 if (!Diags.hasErrorOccurred() && Builder)
254 Builder->Release();
255
256 // If there are errors before or when releasing the Builder, reset
257 // the module to stop here before invoking the backend.
Ted Kremenek7db4f602008-08-07 19:47:41 +0000258 if (Diags.hasErrorOccurred()) {
Rafael Espindolac0ff7442013-12-09 14:59:08 +0000259 if (Builder)
260 Builder->clear();
Ted Kremenek7db4f602008-08-07 19:47:41 +0000261 M.reset();
262 return;
263 }
Daniel Dunbare017ecc2009-12-19 17:50:07 +0000264 }
Douglas Gregorbeecd582009-04-21 17:11:58 +0000265
David Majnemer929025d2016-01-26 19:30:26 +0000266 void AssignInheritanceModel(CXXRecordDecl *RD) override {
267 if (Diags.hasErrorOccurred())
268 return;
269
270 Builder->RefreshTypeCacheForClass(RD);
271 }
272
Craig Topper4f12f102014-03-12 06:41:41 +0000273 void CompleteTentativeDefinition(VarDecl *D) override {
Douglas Gregorbeecd582009-04-21 17:11:58 +0000274 if (Diags.hasErrorOccurred())
275 return;
276
277 Builder->EmitTentativeDefinition(D);
278 }
Douglas Gregor88d292c2010-05-13 16:44:06 +0000279
Nico Weberb6a5d052015-01-15 04:07:35 +0000280 void HandleVTable(CXXRecordDecl *RD) override {
Douglas Gregor88d292c2010-05-13 16:44:06 +0000281 if (Diags.hasErrorOccurred())
282 return;
283
Nico Weberb6a5d052015-01-15 04:07:35 +0000284 Builder->EmitVTable(RD);
Douglas Gregor88d292c2010-05-13 16:44:06 +0000285 }
Chris Lattneradf1f512008-02-06 02:01:47 +0000286 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +0000287}
Chris Lattnerf97fe382007-05-24 06:29:05 +0000288
David Blaikie68e081d2011-12-20 02:48:34 +0000289void CodeGenerator::anchor() { }
290
John McCall6909fee2016-05-18 05:21:18 +0000291CodeGenModule &CodeGenerator::CGM() {
292 return static_cast<CodeGeneratorImpl*>(this)->CGM();
293}
294
295llvm::Module *CodeGenerator::GetModule() {
296 return static_cast<CodeGeneratorImpl*>(this)->GetModule();
297}
298
299llvm::Module *CodeGenerator::ReleaseModule() {
300 return static_cast<CodeGeneratorImpl*>(this)->ReleaseModule();
301}
302
Amjad Aboud546bc112017-02-09 22:07:24 +0000303CGDebugInfo *CodeGenerator::getCGDebugInfo() {
304 return static_cast<CodeGeneratorImpl*>(this)->getCGDebugInfo();
305}
306
John McCall6909fee2016-05-18 05:21:18 +0000307const Decl *CodeGenerator::GetDeclForMangledName(llvm::StringRef name) {
308 return static_cast<CodeGeneratorImpl*>(this)->GetDeclForMangledName(name);
309}
310
311llvm::Constant *CodeGenerator::GetAddrOfGlobal(GlobalDecl global,
312 bool isForDefinition) {
313 return static_cast<CodeGeneratorImpl*>(this)
314 ->GetAddrOfGlobal(global, isForDefinition);
315}
316
Vassil Vassilev4d54e5432017-08-27 10:58:03 +0000317llvm::Module *CodeGenerator::StartModule(llvm::StringRef ModuleName,
318 llvm::LLVMContext &C) {
319 return static_cast<CodeGeneratorImpl*>(this)->StartModule(ModuleName, C);
320}
321
Adrian Prantle74f5252015-06-30 02:26:03 +0000322CodeGenerator *clang::CreateLLVMCodeGen(
John McCall6909fee2016-05-18 05:21:18 +0000323 DiagnosticsEngine &Diags, llvm::StringRef ModuleName,
Adrian Prantle74f5252015-06-30 02:26:03 +0000324 const HeaderSearchOptions &HeaderSearchOpts,
325 const PreprocessorOptions &PreprocessorOpts, const CodeGenOptions &CGO,
326 llvm::LLVMContext &C, CoverageSourceInfo *CoverageInfo) {
327 return new CodeGeneratorImpl(Diags, ModuleName, HeaderSearchOpts,
328 PreprocessorOpts, CGO, C, CoverageInfo);
Chris Lattnerf97fe382007-05-24 06:29:05 +0000329}