blob: 3b4e06045a37c79445dd7b3543a2a6c10d48f453 [file] [log] [blame]
Chris Lattnerf97fe382007-05-24 06:29:05 +00001//===--- ModuleBuilder.cpp - Emit LLVM Code from ASTs ---------------------===//
2//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
Chris Lattnerf97fe382007-05-24 06:29:05 +00006//
7//===----------------------------------------------------------------------===//
8//
9// This builds an AST and converts it to LLVM Code.
10//
11//===----------------------------------------------------------------------===//
12
13#include "clang/CodeGen/ModuleBuilder.h"
David Blaikie48ad6dc2013-07-13 21:08:14 +000014#include "CGDebugInfo.h"
Chandler Carruth5553d0d2014-01-07 11:51:46 +000015#include "CodeGenModule.h"
Chris Lattneradf1f512008-02-06 02:01:47 +000016#include "clang/AST/ASTContext.h"
Daniel Dunbar221fa942008-08-11 04:54:23 +000017#include "clang/AST/DeclObjC.h"
18#include "clang/AST/Expr.h"
Richard Trieu63688182018-12-11 03:18:39 +000019#include "clang/Basic/CodeGenOptions.h"
Chris Lattneradf1f512008-02-06 02:01:47 +000020#include "clang/Basic/Diagnostic.h"
21#include "clang/Basic/TargetInfo.h"
Reid Klecknere43f0fe2013-05-08 13:44:39 +000022#include "llvm/ADT/StringRef.h"
Chandler Carruthffd55512013-01-02 11:45:17 +000023#include "llvm/IR/DataLayout.h"
24#include "llvm/IR/LLVMContext.h"
25#include "llvm/IR/Module.h"
Ahmed Charlesdfca6f92014-03-09 11:36:40 +000026#include <memory>
John McCall6909fee2016-05-18 05:21:18 +000027
Chris Lattner984fac52009-03-26 05:00:52 +000028using namespace clang;
John McCall6909fee2016-05-18 05:21:18 +000029using namespace CodeGen;
Ted Kremenek2c674f62008-08-05 18:50:11 +000030
Chris Lattneradf1f512008-02-06 02:01:47 +000031namespace {
Benjamin Kramer337e3a52009-11-28 19:45:26 +000032 class CodeGeneratorImpl : public CodeGenerator {
David Blaikie9c902b52011-09-25 23:23:43 +000033 DiagnosticsEngine &Diags;
Chris Lattneradf1f512008-02-06 02:01:47 +000034 ASTContext *Ctx;
Adrian Prantle74f5252015-06-30 02:26:03 +000035 const HeaderSearchOptions &HeaderSearchOpts; // Only used for debug info.
36 const PreprocessorOptions &PreprocessorOpts; // Only used for debug info.
Chandler Carruthbc55fe22009-11-12 17:24:48 +000037 const CodeGenOptions CodeGenOpts; // Intentionally copied in.
Richard Smith7f5755c2014-08-01 22:42:16 +000038
39 unsigned HandlingTopLevelDecls;
Reid Klecknerea53dba2016-04-22 18:46:33 +000040
41 /// Use this when emitting decls to block re-entrant decl emission. It will
42 /// emit all deferred decls on scope exit. Set EmitDeferred to false if decl
43 /// emission must be deferred longer, like at the end of a tag definition.
Richard Smith7f5755c2014-08-01 22:42:16 +000044 struct HandlingTopLevelDeclRAII {
45 CodeGeneratorImpl &Self;
Reid Klecknerea53dba2016-04-22 18:46:33 +000046 bool EmitDeferred;
47 HandlingTopLevelDeclRAII(CodeGeneratorImpl &Self,
48 bool EmitDeferred = true)
49 : Self(Self), EmitDeferred(EmitDeferred) {
Richard Smith7f5755c2014-08-01 22:42:16 +000050 ++Self.HandlingTopLevelDecls;
51 }
52 ~HandlingTopLevelDeclRAII() {
Reid Klecknerea53dba2016-04-22 18:46:33 +000053 unsigned Level = --Self.HandlingTopLevelDecls;
54 if (Level == 0 && EmitDeferred)
Richard Smith7f5755c2014-08-01 22:42:16 +000055 Self.EmitDeferredDecls();
56 }
57 };
58
Alex Lorenzee024992014-08-04 18:41:51 +000059 CoverageSourceInfo *CoverageInfo;
60
Chris Lattneradf1f512008-02-06 02:01:47 +000061 protected:
Ahmed Charlesb8984322014-03-07 20:03:18 +000062 std::unique_ptr<llvm::Module> M;
63 std::unique_ptr<CodeGen::CodeGenModule> Builder;
64
Hans Wennborg2b0d0142014-12-18 19:19:00 +000065 private:
Reid Kleckner78381c62018-09-18 23:16:30 +000066 SmallVector<FunctionDecl *, 8> DeferredInlineMemberFuncDefs;
Hans Wennborg2b0d0142014-12-18 19:19:00 +000067
Chris Lattneradf1f512008-02-06 02:01:47 +000068 public:
John McCall6909fee2016-05-18 05:21:18 +000069 CodeGeneratorImpl(DiagnosticsEngine &diags, llvm::StringRef ModuleName,
Adrian Prantle74f5252015-06-30 02:26:03 +000070 const HeaderSearchOptions &HSO,
71 const PreprocessorOptions &PPO, const CodeGenOptions &CGO,
72 llvm::LLVMContext &C,
Alex Lorenzee024992014-08-04 18:41:51 +000073 CoverageSourceInfo *CoverageInfo = nullptr)
Adrian Prantle74f5252015-06-30 02:26:03 +000074 : Diags(diags), Ctx(nullptr), HeaderSearchOpts(HSO),
75 PreprocessorOpts(PPO), CodeGenOpts(CGO), HandlingTopLevelDecls(0),
Mehdi Amini557c20a2016-03-13 21:05:23 +000076 CoverageInfo(CoverageInfo), M(new llvm::Module(ModuleName, C)) {
77 C.setDiscardValueNames(CGO.DiscardValueNames);
78 }
Mike Stump11289f42009-09-09 15:08:12 +000079
Alexander Kornienko34eb2072015-04-11 02:00:23 +000080 ~CodeGeneratorImpl() override {
Hans Wennborg0c0a8c82014-12-19 23:35:11 +000081 // There should normally not be any leftover inline method definitions.
Reid Kleckner78381c62018-09-18 23:16:30 +000082 assert(DeferredInlineMemberFuncDefs.empty() ||
Hans Wennborg0c0a8c82014-12-19 23:35:11 +000083 Diags.hasErrorOccurred());
Hans Wennborg2b0d0142014-12-18 19:19:00 +000084 }
Mike Stump11289f42009-09-09 15:08:12 +000085
John McCall6909fee2016-05-18 05:21:18 +000086 CodeGenModule &CGM() {
87 return *Builder;
88 }
89
90 llvm::Module *GetModule() {
Daniel Dunbar30c514e2008-10-21 19:55:09 +000091 return M.get();
92 }
Mike Stump11289f42009-09-09 15:08:12 +000093
Amjad Aboud546bc112017-02-09 22:07:24 +000094 CGDebugInfo *getCGDebugInfo() {
95 return Builder->getModuleDebugInfo();
96 }
97
John McCall6909fee2016-05-18 05:21:18 +000098 llvm::Module *ReleaseModule() {
99 return M.release();
100 }
101
102 const Decl *GetDeclForMangledName(StringRef MangledName) {
Alp Tokerfb8d02b2014-06-05 22:10:59 +0000103 GlobalDecl Result;
104 if (!Builder->lookupRepresentativeDecl(MangledName, Result))
105 return nullptr;
106 const Decl *D = Result.getCanonicalDecl().getDecl();
107 if (auto FD = dyn_cast<FunctionDecl>(D)) {
108 if (FD->hasBody(FD))
109 return FD;
110 } else if (auto TD = dyn_cast<TagDecl>(D)) {
111 if (auto Def = TD->getDefinition())
112 return Def;
113 }
114 return D;
115 }
116
John McCall6909fee2016-05-18 05:21:18 +0000117 llvm::Constant *GetAddrOfGlobal(GlobalDecl global, bool isForDefinition) {
John McCalld195d4c2016-11-30 23:25:13 +0000118 return Builder->GetAddrOfGlobal(global, ForDefinition_t(isForDefinition));
John McCall6909fee2016-05-18 05:21:18 +0000119 }
Mike Stump11289f42009-09-09 15:08:12 +0000120
Vassil Vassilev4d54e5432017-08-27 10:58:03 +0000121 llvm::Module *StartModule(llvm::StringRef ModuleName,
122 llvm::LLVMContext &C) {
123 assert(!M && "Replacing existing Module?");
124 M.reset(new llvm::Module(ModuleName, C));
125 Initialize(*Ctx);
126 return M.get();
127 }
128
Craig Topper4f12f102014-03-12 06:41:41 +0000129 void Initialize(ASTContext &Context) override {
Chris Lattneradf1f512008-02-06 02:01:47 +0000130 Ctx = &Context;
Mike Stump11289f42009-09-09 15:08:12 +0000131
Douglas Gregore8bbc122011-09-02 00:18:52 +0000132 M->setTargetTriple(Ctx->getTargetInfo().getTriple().getTriple());
James Y Knightb214cbc2016-03-04 19:00:41 +0000133 M->setDataLayout(Ctx->getTargetInfo().getDataLayout());
Alex Lorenz0a264f32018-12-17 19:19:15 +0000134 const auto &SDKVersion = Ctx->getTargetInfo().getSDKVersion();
135 if (!SDKVersion.empty())
136 M->setSDKVersion(SDKVersion);
Mehdi Aminica3cf9e2015-07-24 16:04:29 +0000137 Builder.reset(new CodeGen::CodeGenModule(Context, HeaderSearchOpts,
138 PreprocessorOpts, CodeGenOpts,
139 *M, Diags, CoverageInfo));
Hans Wennborg75958c42013-08-08 00:17:41 +0000140
Peter Collingbournedc134532016-01-16 00:31:22 +0000141 for (auto &&Lib : CodeGenOpts.DependentLibraries)
Nico Weber66220292016-03-02 17:28:48 +0000142 Builder->AddDependentLib(Lib);
Peter Collingbournedc134532016-01-16 00:31:22 +0000143 for (auto &&Opt : CodeGenOpts.LinkerOptions)
Nico Weber66220292016-03-02 17:28:48 +0000144 Builder->AppendLinkerOptions(Opt);
Chris Lattneradf1f512008-02-06 02:01:47 +0000145 }
Mike Stump11289f42009-09-09 15:08:12 +0000146
Craig Topper4f12f102014-03-12 06:41:41 +0000147 void HandleCXXStaticMemberVarInstantiation(VarDecl *VD) override {
David Blaikie4a9ec7b2013-08-19 21:02:26 +0000148 if (Diags.hasErrorOccurred())
149 return;
150
Rafael Espindoladf88f6f2012-03-08 15:51:03 +0000151 Builder->HandleCXXStaticMemberVarInstantiation(VD);
Rafael Espindola189fa742012-03-05 10:54:55 +0000152 }
153
Craig Topper4f12f102014-03-12 06:41:41 +0000154 bool HandleTopLevelDecl(DeclGroupRef DG) override {
David Blaikie4a9ec7b2013-08-19 21:02:26 +0000155 if (Diags.hasErrorOccurred())
156 return true;
157
Richard Smith7f5755c2014-08-01 22:42:16 +0000158 HandlingTopLevelDeclRAII HandlingDecl(*this);
159
Douglas Gregor6e6ad602009-01-20 01:17:11 +0000160 // Make sure to emit all elements of a Decl.
Chris Lattner5bbb3c82009-03-29 16:50:03 +0000161 for (DeclGroupRef::iterator I = DG.begin(), E = DG.end(); I != E; ++I)
162 Builder->EmitTopLevelDecl(*I);
Hans Wennborgdfcb7d62014-06-06 17:36:17 +0000163
Richard Smith7f5755c2014-08-01 22:42:16 +0000164 return true;
165 }
166
167 void EmitDeferredDecls() {
Reid Kleckner78381c62018-09-18 23:16:30 +0000168 if (DeferredInlineMemberFuncDefs.empty())
Richard Smithc9cbde72014-08-13 21:15:09 +0000169 return;
170
Richard Smith1ba0a072014-08-01 20:39:36 +0000171 // Emit any deferred inline method definitions. Note that more deferred
172 // methods may be added during this loop, since ASTConsumer callbacks
173 // can be invoked if AST inspection results in declarations being added.
Richard Smithc9cbde72014-08-13 21:15:09 +0000174 HandlingTopLevelDeclRAII HandlingDecl(*this);
Reid Kleckner78381c62018-09-18 23:16:30 +0000175 for (unsigned I = 0; I != DeferredInlineMemberFuncDefs.size(); ++I)
176 Builder->EmitTopLevelDecl(DeferredInlineMemberFuncDefs[I]);
177 DeferredInlineMemberFuncDefs.clear();
Chris Lattneradf1f512008-02-06 02:01:47 +0000178 }
Daniel Dunbarfce4be82008-08-15 23:26:23 +0000179
Stephan Bergmann17d7d142016-03-30 06:27:31 +0000180 void HandleInlineFunctionDefinition(FunctionDecl *D) override {
Hans Wennborga926d842014-05-23 20:37:38 +0000181 if (Diags.hasErrorOccurred())
182 return;
183
184 assert(D->doesThisDeclarationHaveABody());
185
Hans Wennborgdfcb7d62014-06-06 17:36:17 +0000186 // We may want to emit this definition. However, that decision might be
187 // based on computing the linkage, and we have to defer that in case we
188 // are inside of something that will change the method's final linkage,
189 // e.g.
190 // typedef struct {
191 // void bar();
192 // void foo() { bar(); }
193 // } A;
Reid Kleckner78381c62018-09-18 23:16:30 +0000194 DeferredInlineMemberFuncDefs.push_back(D);
Alex Lorenzee024992014-08-04 18:41:51 +0000195
Justin Bogner94d384e2014-11-18 00:34:46 +0000196 // Provide some coverage mapping even for methods that aren't emitted.
197 // Don't do this for templated classes though, as they may not be
198 // instantiable.
Reid Kleckner78381c62018-09-18 23:16:30 +0000199 if (!D->getLexicalDeclContext()->isDependentContext())
200 Builder->AddDeferredUnusedCoverageMapping(D);
Hans Wennborga926d842014-05-23 20:37:38 +0000201 }
202
Chris Lattnera5e4d302008-02-06 04:51:19 +0000203 /// HandleTagDeclDefinition - This callback is invoked each time a TagDecl
Chris Lattner5bbb3c82009-03-29 16:50:03 +0000204 /// to (e.g. struct, union, enum, class) is completed. This allows the
205 /// client hack on the type, which can occur at any point in the file
206 /// (because these can be defined in declspecs).
Craig Topper4f12f102014-03-12 06:41:41 +0000207 void HandleTagDeclDefinition(TagDecl *D) override {
David Blaikie4a9ec7b2013-08-19 21:02:26 +0000208 if (Diags.hasErrorOccurred())
209 return;
210
Reid Klecknerea53dba2016-04-22 18:46:33 +0000211 // Don't allow re-entrant calls to CodeGen triggered by PCH
212 // deserialization to emit deferred decls.
213 HandlingTopLevelDeclRAII HandlingDecl(*this, /*EmitDeferred=*/false);
214
Chris Lattner68be6062008-02-06 05:08:19 +0000215 Builder->UpdateCompletedType(D);
Hans Wennborg56fc62b2014-07-17 20:25:23 +0000216
217 // For MSVC compatibility, treat declarations of static data members with
218 // inline initializers as definitions.
David Majnemer3f021502015-10-08 04:53:31 +0000219 if (Ctx->getTargetInfo().getCXXABI().isMicrosoft()) {
Hans Wennborg56fc62b2014-07-17 20:25:23 +0000220 for (Decl *Member : D->decls()) {
221 if (VarDecl *VD = dyn_cast<VarDecl>(Member)) {
222 if (Ctx->isMSStaticDataMemberInlineDefinition(VD) &&
223 Ctx->DeclMustBeEmitted(VD)) {
224 Builder->EmitGlobal(VD);
225 }
226 }
227 }
228 }
Alexey Bataevc5b1d322016-03-04 09:22:22 +0000229 // For OpenMP emit declare reduction functions, if required.
230 if (Ctx->getLangOpts().OpenMP) {
231 for (Decl *Member : D->decls()) {
232 if (auto *DRD = dyn_cast<OMPDeclareReductionDecl>(Member)) {
233 if (Ctx->DeclMustBeEmitted(DRD))
234 Builder->EmitGlobal(DRD);
235 }
236 }
237 }
Chris Lattnera5e4d302008-02-06 04:51:19 +0000238 }
Ted Kremenek7db4f602008-08-07 19:47:41 +0000239
Craig Topper4f12f102014-03-12 06:41:41 +0000240 void HandleTagDeclRequiredDefinition(const TagDecl *D) override {
David Blaikie4a9ec7b2013-08-19 21:02:26 +0000241 if (Diags.hasErrorOccurred())
242 return;
243
Reid Klecknerea53dba2016-04-22 18:46:33 +0000244 // Don't allow re-entrant calls to CodeGen triggered by PCH
245 // deserialization to emit deferred decls.
246 HandlingTopLevelDeclRAII HandlingDecl(*this, /*EmitDeferred=*/false);
247
David Blaikie48ad6dc2013-07-13 21:08:14 +0000248 if (CodeGen::CGDebugInfo *DI = Builder->getModuleDebugInfo())
249 if (const RecordDecl *RD = dyn_cast<RecordDecl>(D))
David Blaikieb2e86eb2013-08-15 20:49:17 +0000250 DI->completeRequiredType(RD);
David Blaikie48ad6dc2013-07-13 21:08:14 +0000251 }
252
Craig Topper4f12f102014-03-12 06:41:41 +0000253 void HandleTranslationUnit(ASTContext &Ctx) override {
Manman Ren581c2b92016-01-28 23:29:02 +0000254 // Release the Builder when there is no error.
255 if (!Diags.hasErrorOccurred() && Builder)
256 Builder->Release();
257
258 // If there are errors before or when releasing the Builder, reset
259 // the module to stop here before invoking the backend.
Ted Kremenek7db4f602008-08-07 19:47:41 +0000260 if (Diags.hasErrorOccurred()) {
Rafael Espindolac0ff7442013-12-09 14:59:08 +0000261 if (Builder)
262 Builder->clear();
Ted Kremenek7db4f602008-08-07 19:47:41 +0000263 M.reset();
264 return;
265 }
Daniel Dunbare017ecc2009-12-19 17:50:07 +0000266 }
Douglas Gregorbeecd582009-04-21 17:11:58 +0000267
David Majnemer929025d2016-01-26 19:30:26 +0000268 void AssignInheritanceModel(CXXRecordDecl *RD) override {
269 if (Diags.hasErrorOccurred())
270 return;
271
272 Builder->RefreshTypeCacheForClass(RD);
273 }
274
Craig Topper4f12f102014-03-12 06:41:41 +0000275 void CompleteTentativeDefinition(VarDecl *D) override {
Douglas Gregorbeecd582009-04-21 17:11:58 +0000276 if (Diags.hasErrorOccurred())
277 return;
278
279 Builder->EmitTentativeDefinition(D);
280 }
Douglas Gregor88d292c2010-05-13 16:44:06 +0000281
Nico Weberb6a5d052015-01-15 04:07:35 +0000282 void HandleVTable(CXXRecordDecl *RD) override {
Douglas Gregor88d292c2010-05-13 16:44:06 +0000283 if (Diags.hasErrorOccurred())
284 return;
285
Nico Weberb6a5d052015-01-15 04:07:35 +0000286 Builder->EmitVTable(RD);
Douglas Gregor88d292c2010-05-13 16:44:06 +0000287 }
Chris Lattneradf1f512008-02-06 02:01:47 +0000288 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +0000289}
Chris Lattnerf97fe382007-05-24 06:29:05 +0000290
David Blaikie68e081d2011-12-20 02:48:34 +0000291void CodeGenerator::anchor() { }
292
John McCall6909fee2016-05-18 05:21:18 +0000293CodeGenModule &CodeGenerator::CGM() {
294 return static_cast<CodeGeneratorImpl*>(this)->CGM();
295}
296
297llvm::Module *CodeGenerator::GetModule() {
298 return static_cast<CodeGeneratorImpl*>(this)->GetModule();
299}
300
301llvm::Module *CodeGenerator::ReleaseModule() {
302 return static_cast<CodeGeneratorImpl*>(this)->ReleaseModule();
303}
304
Amjad Aboud546bc112017-02-09 22:07:24 +0000305CGDebugInfo *CodeGenerator::getCGDebugInfo() {
306 return static_cast<CodeGeneratorImpl*>(this)->getCGDebugInfo();
307}
308
John McCall6909fee2016-05-18 05:21:18 +0000309const Decl *CodeGenerator::GetDeclForMangledName(llvm::StringRef name) {
310 return static_cast<CodeGeneratorImpl*>(this)->GetDeclForMangledName(name);
311}
312
313llvm::Constant *CodeGenerator::GetAddrOfGlobal(GlobalDecl global,
314 bool isForDefinition) {
315 return static_cast<CodeGeneratorImpl*>(this)
316 ->GetAddrOfGlobal(global, isForDefinition);
317}
318
Vassil Vassilev4d54e5432017-08-27 10:58:03 +0000319llvm::Module *CodeGenerator::StartModule(llvm::StringRef ModuleName,
320 llvm::LLVMContext &C) {
321 return static_cast<CodeGeneratorImpl*>(this)->StartModule(ModuleName, C);
322}
323
Adrian Prantle74f5252015-06-30 02:26:03 +0000324CodeGenerator *clang::CreateLLVMCodeGen(
John McCall6909fee2016-05-18 05:21:18 +0000325 DiagnosticsEngine &Diags, llvm::StringRef ModuleName,
Adrian Prantle74f5252015-06-30 02:26:03 +0000326 const HeaderSearchOptions &HeaderSearchOpts,
327 const PreprocessorOptions &PreprocessorOpts, const CodeGenOptions &CGO,
328 llvm::LLVMContext &C, CoverageSourceInfo *CoverageInfo) {
329 return new CodeGeneratorImpl(Diags, ModuleName, HeaderSearchOpts,
330 PreprocessorOpts, CGO, C, CoverageInfo);
Chris Lattnerf97fe382007-05-24 06:29:05 +0000331}