blob: 952d1627fa8460597fee700888d5239d8329d66a [file] [log] [blame]
Reid Spencer5f016e22007-07-11 17:01:13 +00001//===--- ModuleBuilder.cpp - Emit LLVM Code from ASTs ---------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner0bc735f2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Reid Spencer5f016e22007-07-11 17:01:13 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This builds an AST and converts it to LLVM Code.
11//
12//===----------------------------------------------------------------------===//
13
14#include "clang/CodeGen/ModuleBuilder.h"
David Blaikie658cd2c2013-07-13 21:08:14 +000015#include "CGDebugInfo.h"
Stephen Hines651f13c2014-04-23 16:59:28 -070016#include "CodeGenModule.h"
Chris Lattner8ee3c032008-02-06 02:01:47 +000017#include "clang/AST/ASTContext.h"
Daniel Dunbare91593e2008-08-11 04:54:23 +000018#include "clang/AST/DeclObjC.h"
19#include "clang/AST/Expr.h"
Chris Lattner8ee3c032008-02-06 02:01:47 +000020#include "clang/Basic/Diagnostic.h"
21#include "clang/Basic/TargetInfo.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000022#include "clang/Frontend/CodeGenOptions.h"
Reid Kleckner3190ca92013-05-08 13:44:39 +000023#include "llvm/ADT/StringRef.h"
Chandler Carruth3b844ba2013-01-02 11:45:17 +000024#include "llvm/IR/DataLayout.h"
25#include "llvm/IR/LLVMContext.h"
26#include "llvm/IR/Module.h"
Stephen Hines651f13c2014-04-23 16:59:28 -070027#include <memory>
Pirama Arumuga Nainar4967a712016-09-19 22:19:55 -070028
Chris Lattnerbd360642009-03-26 05:00:52 +000029using namespace clang;
Pirama Arumuga Nainar4967a712016-09-19 22:19:55 -070030using namespace CodeGen;
Ted Kremenek815c78f2008-08-05 18:50:11 +000031
Chris Lattner8ee3c032008-02-06 02:01:47 +000032namespace {
Benjamin Kramer85b45212009-11-28 19:45:26 +000033 class CodeGeneratorImpl : public CodeGenerator {
David Blaikied6471f72011-09-25 23:23:43 +000034 DiagnosticsEngine &Diags;
Chris Lattner8ee3c032008-02-06 02:01:47 +000035 ASTContext *Ctx;
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -080036 const HeaderSearchOptions &HeaderSearchOpts; // Only used for debug info.
37 const PreprocessorOptions &PreprocessorOpts; // Only used for debug info.
Chandler Carruth2811ccf2009-11-12 17:24:48 +000038 const CodeGenOptions CodeGenOpts; // Intentionally copied in.
Stephen Hines176edba2014-12-01 14:53:08 -080039
40 unsigned HandlingTopLevelDecls;
Pirama Arumuga Nainar4967a712016-09-19 22:19:55 -070041
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.
Stephen Hines176edba2014-12-01 14:53:08 -080045 struct HandlingTopLevelDeclRAII {
46 CodeGeneratorImpl &Self;
Pirama Arumuga Nainar4967a712016-09-19 22:19:55 -070047 bool EmitDeferred;
48 HandlingTopLevelDeclRAII(CodeGeneratorImpl &Self,
49 bool EmitDeferred = true)
50 : Self(Self), EmitDeferred(EmitDeferred) {
Stephen Hines176edba2014-12-01 14:53:08 -080051 ++Self.HandlingTopLevelDecls;
52 }
53 ~HandlingTopLevelDeclRAII() {
Pirama Arumuga Nainar4967a712016-09-19 22:19:55 -070054 unsigned Level = --Self.HandlingTopLevelDecls;
55 if (Level == 0 && EmitDeferred)
Stephen Hines176edba2014-12-01 14:53:08 -080056 Self.EmitDeferredDecls();
57 }
58 };
59
60 CoverageSourceInfo *CoverageInfo;
61
Chris Lattner8ee3c032008-02-06 02:01:47 +000062 protected:
Stephen Hines651f13c2014-04-23 16:59:28 -070063 std::unique_ptr<llvm::Module> M;
64 std::unique_ptr<CodeGen::CodeGenModule> Builder;
65
Stephen Hines0e2c34f2015-03-23 12:09:02 -070066 private:
67 SmallVector<CXXMethodDecl *, 8> DeferredInlineMethodDefinitions;
68
Chris Lattner8ee3c032008-02-06 02:01:47 +000069 public:
Pirama Arumuga Nainar4967a712016-09-19 22:19:55 -070070 CodeGeneratorImpl(DiagnosticsEngine &diags, llvm::StringRef ModuleName,
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -080071 const HeaderSearchOptions &HSO,
72 const PreprocessorOptions &PPO, const CodeGenOptions &CGO,
73 llvm::LLVMContext &C,
Stephen Hines176edba2014-12-01 14:53:08 -080074 CoverageSourceInfo *CoverageInfo = nullptr)
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -080075 : Diags(diags), Ctx(nullptr), HeaderSearchOpts(HSO),
76 PreprocessorOpts(PPO), CodeGenOpts(CGO), HandlingTopLevelDecls(0),
Pirama Arumuga Nainar4967a712016-09-19 22:19:55 -070077 CoverageInfo(CoverageInfo), M(new llvm::Module(ModuleName, C)) {
78 C.setDiscardValueNames(CGO.DiscardValueNames);
79 }
Mike Stump1eb44332009-09-09 15:08:12 +000080
Pirama Arumuga Nainar58878f82015-05-06 11:48:57 -070081 ~CodeGeneratorImpl() override {
Stephen Hines0e2c34f2015-03-23 12:09:02 -070082 // There should normally not be any leftover inline method definitions.
83 assert(DeferredInlineMethodDefinitions.empty() ||
84 Diags.hasErrorOccurred());
85 }
Mike Stump1eb44332009-09-09 15:08:12 +000086
Pirama Arumuga Nainar4967a712016-09-19 22:19:55 -070087 CodeGenModule &CGM() {
88 return *Builder;
89 }
90
91 llvm::Module *GetModule() {
Daniel Dunbard8c0ea12008-10-21 19:55:09 +000092 return M.get();
93 }
Mike Stump1eb44332009-09-09 15:08:12 +000094
Pirama Arumuga Nainar4967a712016-09-19 22:19:55 -070095 llvm::Module *ReleaseModule() {
96 return M.release();
97 }
98
99 const Decl *GetDeclForMangledName(StringRef MangledName) {
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700100 GlobalDecl Result;
101 if (!Builder->lookupRepresentativeDecl(MangledName, Result))
102 return nullptr;
103 const Decl *D = Result.getCanonicalDecl().getDecl();
104 if (auto FD = dyn_cast<FunctionDecl>(D)) {
105 if (FD->hasBody(FD))
106 return FD;
107 } else if (auto TD = dyn_cast<TagDecl>(D)) {
108 if (auto Def = TD->getDefinition())
109 return Def;
110 }
111 return D;
112 }
113
Pirama Arumuga Nainar4967a712016-09-19 22:19:55 -0700114 llvm::Constant *GetAddrOfGlobal(GlobalDecl global, bool isForDefinition) {
115 return Builder->GetAddrOfGlobal(global, isForDefinition);
116 }
Mike Stump1eb44332009-09-09 15:08:12 +0000117
Stephen Hines651f13c2014-04-23 16:59:28 -0700118 void Initialize(ASTContext &Context) override {
Chris Lattner8ee3c032008-02-06 02:01:47 +0000119 Ctx = &Context;
Mike Stump1eb44332009-09-09 15:08:12 +0000120
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000121 M->setTargetTriple(Ctx->getTargetInfo().getTriple().getTriple());
Pirama Arumuga Nainar4967a712016-09-19 22:19:55 -0700122 M->setDataLayout(Ctx->getTargetInfo().getDataLayout());
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -0800123 Builder.reset(new CodeGen::CodeGenModule(Context, HeaderSearchOpts,
124 PreprocessorOpts, CodeGenOpts,
125 *M, Diags, CoverageInfo));
Hans Wennborgb3574792013-08-08 00:17:41 +0000126
Pirama Arumuga Nainar4967a712016-09-19 22:19:55 -0700127 for (auto &&Lib : CodeGenOpts.DependentLibraries)
128 Builder->AddDependentLib(Lib);
129 for (auto &&Opt : CodeGenOpts.LinkerOptions)
130 Builder->AppendLinkerOptions(Opt);
Chris Lattner8ee3c032008-02-06 02:01:47 +0000131 }
Mike Stump1eb44332009-09-09 15:08:12 +0000132
Stephen Hines651f13c2014-04-23 16:59:28 -0700133 void HandleCXXStaticMemberVarInstantiation(VarDecl *VD) override {
David Blaikie0a1c8622013-08-19 21:02:26 +0000134 if (Diags.hasErrorOccurred())
135 return;
136
Rafael Espindola02503932012-03-08 15:51:03 +0000137 Builder->HandleCXXStaticMemberVarInstantiation(VD);
Rafael Espindola234fe652012-03-05 10:54:55 +0000138 }
139
Stephen Hines651f13c2014-04-23 16:59:28 -0700140 bool HandleTopLevelDecl(DeclGroupRef DG) override {
David Blaikie0a1c8622013-08-19 21:02:26 +0000141 if (Diags.hasErrorOccurred())
142 return true;
143
Stephen Hines176edba2014-12-01 14:53:08 -0800144 HandlingTopLevelDeclRAII HandlingDecl(*this);
145
Douglas Gregor4afa39d2009-01-20 01:17:11 +0000146 // Make sure to emit all elements of a Decl.
Chris Lattner682bf922009-03-29 16:50:03 +0000147 for (DeclGroupRef::iterator I = DG.begin(), E = DG.end(); I != E; ++I)
148 Builder->EmitTopLevelDecl(*I);
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700149
Argyrios Kyrtzidis88c25962011-11-18 00:26:59 +0000150 return true;
Chris Lattner8ee3c032008-02-06 02:01:47 +0000151 }
Daniel Dunbar41071de2008-08-15 23:26:23 +0000152
Stephen Hines176edba2014-12-01 14:53:08 -0800153 void EmitDeferredDecls() {
154 if (DeferredInlineMethodDefinitions.empty())
155 return;
156
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();
164 }
165
Pirama Arumuga Nainar4967a712016-09-19 22:19:55 -0700166 void HandleInlineFunctionDefinition(FunctionDecl *D) override {
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700167 if (Diags.hasErrorOccurred())
168 return;
169
170 assert(D->doesThisDeclarationHaveABody());
171
Pirama Arumuga Nainar4967a712016-09-19 22:19:55 -0700172 // Handle friend functions.
173 if (D->isInIdentifierNamespace(Decl::IDNS_OrdinaryFriend)) {
174 if (Ctx->getTargetInfo().getCXXABI().isMicrosoft()
175 && !D->getLexicalDeclContext()->isDependentContext())
176 Builder->EmitTopLevelDecl(D);
177 return;
178 }
179
180 // Otherwise, must be a method.
181 auto MD = cast<CXXMethodDecl>(D);
182
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700183 // 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,
186 // e.g.
187 // typedef struct {
188 // void bar();
189 // void foo() { bar(); }
190 // } A;
Pirama Arumuga Nainar4967a712016-09-19 22:19:55 -0700191 DeferredInlineMethodDefinitions.push_back(MD);
Stephen Hines176edba2014-12-01 14:53:08 -0800192
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
195 // instantiable.
Pirama Arumuga Nainar4967a712016-09-19 22:19:55 -0700196 if (!MD->getParent()->getDescribedClassTemplate())
197 Builder->AddDeferredUnusedCoverageMapping(MD);
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700198 }
199
Chris Lattner9eee0f82008-02-06 04:51:19 +0000200 /// HandleTagDeclDefinition - This callback is invoked each time a TagDecl
Chris Lattner682bf922009-03-29 16:50:03 +0000201 /// 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).
Stephen Hines651f13c2014-04-23 16:59:28 -0700204 void HandleTagDeclDefinition(TagDecl *D) override {
David Blaikie0a1c8622013-08-19 21:02:26 +0000205 if (Diags.hasErrorOccurred())
206 return;
207
Pirama Arumuga Nainar4967a712016-09-19 22:19:55 -0700208 // Don't allow re-entrant calls to CodeGen triggered by PCH
209 // deserialization to emit deferred decls.
210 HandlingTopLevelDeclRAII HandlingDecl(*this, /*EmitDeferred=*/false);
211
Chris Lattnerc5b88062008-02-06 05:08:19 +0000212 Builder->UpdateCompletedType(D);
Stephen Hines176edba2014-12-01 14:53:08 -0800213
214 // For MSVC compatibility, treat declarations of static data members with
215 // inline initializers as definitions.
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -0800216 if (Ctx->getTargetInfo().getCXXABI().isMicrosoft()) {
Stephen Hines176edba2014-12-01 14:53:08 -0800217 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);
222 }
223 }
224 }
225 }
Pirama Arumuga Nainar4967a712016-09-19 22:19:55 -0700226 // 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);
232 }
233 }
234 }
Chris Lattner9eee0f82008-02-06 04:51:19 +0000235 }
Ted Kremenek159346a2008-08-07 19:47:41 +0000236
Stephen Hines651f13c2014-04-23 16:59:28 -0700237 void HandleTagDeclRequiredDefinition(const TagDecl *D) override {
David Blaikie0a1c8622013-08-19 21:02:26 +0000238 if (Diags.hasErrorOccurred())
239 return;
240
Pirama Arumuga Nainar4967a712016-09-19 22:19:55 -0700241 // Don't allow re-entrant calls to CodeGen triggered by PCH
242 // deserialization to emit deferred decls.
243 HandlingTopLevelDeclRAII HandlingDecl(*this, /*EmitDeferred=*/false);
244
David Blaikie658cd2c2013-07-13 21:08:14 +0000245 if (CodeGen::CGDebugInfo *DI = Builder->getModuleDebugInfo())
246 if (const RecordDecl *RD = dyn_cast<RecordDecl>(D))
David Blaikie27804892013-08-15 20:49:17 +0000247 DI->completeRequiredType(RD);
David Blaikie658cd2c2013-07-13 21:08:14 +0000248 }
249
Stephen Hines651f13c2014-04-23 16:59:28 -0700250 void HandleTranslationUnit(ASTContext &Ctx) override {
Pirama Arumuga Nainar4967a712016-09-19 22:19:55 -0700251 // Release the Builder when there is no error.
252 if (!Diags.hasErrorOccurred() && Builder)
253 Builder->Release();
254
255 // If there are errors before or when releasing the Builder, reset
256 // the module to stop here before invoking the backend.
Ted Kremenek159346a2008-08-07 19:47:41 +0000257 if (Diags.hasErrorOccurred()) {
Stephen Hines651f13c2014-04-23 16:59:28 -0700258 if (Builder)
259 Builder->clear();
Ted Kremenek159346a2008-08-07 19:47:41 +0000260 M.reset();
261 return;
262 }
Pirama Arumuga Nainar4967a712016-09-19 22:19:55 -0700263 }
Ted Kremenek159346a2008-08-07 19:47:41 +0000264
Pirama Arumuga Nainar4967a712016-09-19 22:19:55 -0700265 void AssignInheritanceModel(CXXRecordDecl *RD) override {
266 if (Diags.hasErrorOccurred())
267 return;
268
269 Builder->RefreshTypeCacheForClass(RD);
Daniel Dunbar7177dee2009-12-19 17:50:07 +0000270 }
Douglas Gregorb6c8c8b2009-04-21 17:11:58 +0000271
Stephen Hines651f13c2014-04-23 16:59:28 -0700272 void CompleteTentativeDefinition(VarDecl *D) override {
Douglas Gregorb6c8c8b2009-04-21 17:11:58 +0000273 if (Diags.hasErrorOccurred())
274 return;
275
276 Builder->EmitTentativeDefinition(D);
277 }
Douglas Gregor6fb745b2010-05-13 16:44:06 +0000278
Stephen Hines0e2c34f2015-03-23 12:09:02 -0700279 void HandleVTable(CXXRecordDecl *RD) override {
Douglas Gregor6fb745b2010-05-13 16:44:06 +0000280 if (Diags.hasErrorOccurred())
281 return;
282
Stephen Hines0e2c34f2015-03-23 12:09:02 -0700283 Builder->EmitVTable(RD);
Douglas Gregor6fb745b2010-05-13 16:44:06 +0000284 }
Chris Lattner8ee3c032008-02-06 02:01:47 +0000285 };
Reid Spencer5f016e22007-07-11 17:01:13 +0000286}
287
David Blaikie99ba9e32011-12-20 02:48:34 +0000288void CodeGenerator::anchor() { }
289
Pirama Arumuga Nainar4967a712016-09-19 22:19:55 -0700290CodeGenModule &CodeGenerator::CGM() {
291 return static_cast<CodeGeneratorImpl*>(this)->CGM();
292}
293
294llvm::Module *CodeGenerator::GetModule() {
295 return static_cast<CodeGeneratorImpl*>(this)->GetModule();
296}
297
298llvm::Module *CodeGenerator::ReleaseModule() {
299 return static_cast<CodeGeneratorImpl*>(this)->ReleaseModule();
300}
301
302const Decl *CodeGenerator::GetDeclForMangledName(llvm::StringRef name) {
303 return static_cast<CodeGeneratorImpl*>(this)->GetDeclForMangledName(name);
304}
305
306llvm::Constant *CodeGenerator::GetAddrOfGlobal(GlobalDecl global,
307 bool isForDefinition) {
308 return static_cast<CodeGeneratorImpl*>(this)
309 ->GetAddrOfGlobal(global, isForDefinition);
310}
311
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -0800312CodeGenerator *clang::CreateLLVMCodeGen(
Pirama Arumuga Nainar4967a712016-09-19 22:19:55 -0700313 DiagnosticsEngine &Diags, llvm::StringRef ModuleName,
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -0800314 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);
Reid Spencer5f016e22007-07-11 17:01:13 +0000319}