blob: 042712965b0066647e5ad6f2be4a214b2479b302 [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>
Chris Lattner984fac52009-03-26 05:00:52 +000028using namespace clang;
Ted Kremenek2c674f62008-08-05 18:50:11 +000029
Chris Lattneradf1f512008-02-06 02:01:47 +000030namespace {
Benjamin Kramer337e3a52009-11-28 19:45:26 +000031 class CodeGeneratorImpl : public CodeGenerator {
David Blaikie9c902b52011-09-25 23:23:43 +000032 DiagnosticsEngine &Diags;
Chris Lattneradf1f512008-02-06 02:01:47 +000033 ASTContext *Ctx;
Adrian Prantle74f5252015-06-30 02:26:03 +000034 const HeaderSearchOptions &HeaderSearchOpts; // Only used for debug info.
35 const PreprocessorOptions &PreprocessorOpts; // Only used for debug info.
Chandler Carruthbc55fe22009-11-12 17:24:48 +000036 const CodeGenOptions CodeGenOpts; // Intentionally copied in.
Richard Smith7f5755c2014-08-01 22:42:16 +000037
38 unsigned HandlingTopLevelDecls;
Reid Klecknerea53dba2016-04-22 18:46:33 +000039
40 /// Use this when emitting decls to block re-entrant decl emission. It will
41 /// emit all deferred decls on scope exit. Set EmitDeferred to false if decl
42 /// emission must be deferred longer, like at the end of a tag definition.
Richard Smith7f5755c2014-08-01 22:42:16 +000043 struct HandlingTopLevelDeclRAII {
44 CodeGeneratorImpl &Self;
Reid Klecknerea53dba2016-04-22 18:46:33 +000045 bool EmitDeferred;
46 HandlingTopLevelDeclRAII(CodeGeneratorImpl &Self,
47 bool EmitDeferred = true)
48 : Self(Self), EmitDeferred(EmitDeferred) {
Richard Smith7f5755c2014-08-01 22:42:16 +000049 ++Self.HandlingTopLevelDecls;
50 }
51 ~HandlingTopLevelDeclRAII() {
Reid Klecknerea53dba2016-04-22 18:46:33 +000052 unsigned Level = --Self.HandlingTopLevelDecls;
53 if (Level == 0 && EmitDeferred)
Richard Smith7f5755c2014-08-01 22:42:16 +000054 Self.EmitDeferredDecls();
55 }
56 };
57
Alex Lorenzee024992014-08-04 18:41:51 +000058 CoverageSourceInfo *CoverageInfo;
59
Chris Lattneradf1f512008-02-06 02:01:47 +000060 protected:
Ahmed Charlesb8984322014-03-07 20:03:18 +000061 std::unique_ptr<llvm::Module> M;
62 std::unique_ptr<CodeGen::CodeGenModule> Builder;
63
Hans Wennborg2b0d0142014-12-18 19:19:00 +000064 private:
65 SmallVector<CXXMethodDecl *, 8> DeferredInlineMethodDefinitions;
66
Chris Lattneradf1f512008-02-06 02:01:47 +000067 public:
Adrian Prantle74f5252015-06-30 02:26:03 +000068 CodeGeneratorImpl(DiagnosticsEngine &diags, const std::string &ModuleName,
69 const HeaderSearchOptions &HSO,
70 const PreprocessorOptions &PPO, const CodeGenOptions &CGO,
71 llvm::LLVMContext &C,
Alex Lorenzee024992014-08-04 18:41:51 +000072 CoverageSourceInfo *CoverageInfo = nullptr)
Adrian Prantle74f5252015-06-30 02:26:03 +000073 : Diags(diags), Ctx(nullptr), HeaderSearchOpts(HSO),
74 PreprocessorOpts(PPO), CodeGenOpts(CGO), HandlingTopLevelDecls(0),
Mehdi Amini557c20a2016-03-13 21:05:23 +000075 CoverageInfo(CoverageInfo), M(new llvm::Module(ModuleName, C)) {
76 C.setDiscardValueNames(CGO.DiscardValueNames);
77 }
Mike Stump11289f42009-09-09 15:08:12 +000078
Alexander Kornienko34eb2072015-04-11 02:00:23 +000079 ~CodeGeneratorImpl() override {
Hans Wennborg0c0a8c82014-12-19 23:35:11 +000080 // There should normally not be any leftover inline method definitions.
81 assert(DeferredInlineMethodDefinitions.empty() ||
82 Diags.hasErrorOccurred());
Hans Wennborg2b0d0142014-12-18 19:19:00 +000083 }
Mike Stump11289f42009-09-09 15:08:12 +000084
Craig Topper4f12f102014-03-12 06:41:41 +000085 llvm::Module* GetModule() override {
Daniel Dunbar30c514e2008-10-21 19:55:09 +000086 return M.get();
87 }
Mike Stump11289f42009-09-09 15:08:12 +000088
Alp Tokerfb8d02b2014-06-05 22:10:59 +000089 const Decl *GetDeclForMangledName(StringRef MangledName) override {
90 GlobalDecl Result;
91 if (!Builder->lookupRepresentativeDecl(MangledName, Result))
92 return nullptr;
93 const Decl *D = Result.getCanonicalDecl().getDecl();
94 if (auto FD = dyn_cast<FunctionDecl>(D)) {
95 if (FD->hasBody(FD))
96 return FD;
97 } else if (auto TD = dyn_cast<TagDecl>(D)) {
98 if (auto Def = TD->getDefinition())
99 return Def;
100 }
101 return D;
102 }
103
Craig Topper4f12f102014-03-12 06:41:41 +0000104 llvm::Module *ReleaseModule() override { return M.release(); }
Mike Stump11289f42009-09-09 15:08:12 +0000105
Craig Topper4f12f102014-03-12 06:41:41 +0000106 void Initialize(ASTContext &Context) override {
Chris Lattneradf1f512008-02-06 02:01:47 +0000107 Ctx = &Context;
Mike Stump11289f42009-09-09 15:08:12 +0000108
Douglas Gregore8bbc122011-09-02 00:18:52 +0000109 M->setTargetTriple(Ctx->getTargetInfo().getTriple().getTriple());
James Y Knightb214cbc2016-03-04 19:00:41 +0000110 M->setDataLayout(Ctx->getTargetInfo().getDataLayout());
Mehdi Aminica3cf9e2015-07-24 16:04:29 +0000111 Builder.reset(new CodeGen::CodeGenModule(Context, HeaderSearchOpts,
112 PreprocessorOpts, CodeGenOpts,
113 *M, Diags, CoverageInfo));
Hans Wennborg75958c42013-08-08 00:17:41 +0000114
Peter Collingbournedc134532016-01-16 00:31:22 +0000115 for (auto &&Lib : CodeGenOpts.DependentLibraries)
Nico Weber66220292016-03-02 17:28:48 +0000116 Builder->AddDependentLib(Lib);
Peter Collingbournedc134532016-01-16 00:31:22 +0000117 for (auto &&Opt : CodeGenOpts.LinkerOptions)
Nico Weber66220292016-03-02 17:28:48 +0000118 Builder->AppendLinkerOptions(Opt);
Chris Lattneradf1f512008-02-06 02:01:47 +0000119 }
Mike Stump11289f42009-09-09 15:08:12 +0000120
Craig Topper4f12f102014-03-12 06:41:41 +0000121 void HandleCXXStaticMemberVarInstantiation(VarDecl *VD) override {
David Blaikie4a9ec7b2013-08-19 21:02:26 +0000122 if (Diags.hasErrorOccurred())
123 return;
124
Rafael Espindoladf88f6f2012-03-08 15:51:03 +0000125 Builder->HandleCXXStaticMemberVarInstantiation(VD);
Rafael Espindola189fa742012-03-05 10:54:55 +0000126 }
127
Craig Topper4f12f102014-03-12 06:41:41 +0000128 bool HandleTopLevelDecl(DeclGroupRef DG) override {
David Blaikie4a9ec7b2013-08-19 21:02:26 +0000129 if (Diags.hasErrorOccurred())
130 return true;
131
Richard Smith7f5755c2014-08-01 22:42:16 +0000132 HandlingTopLevelDeclRAII HandlingDecl(*this);
133
Douglas Gregor6e6ad602009-01-20 01:17:11 +0000134 // Make sure to emit all elements of a Decl.
Chris Lattner5bbb3c82009-03-29 16:50:03 +0000135 for (DeclGroupRef::iterator I = DG.begin(), E = DG.end(); I != E; ++I)
136 Builder->EmitTopLevelDecl(*I);
Hans Wennborgdfcb7d62014-06-06 17:36:17 +0000137
Richard Smith7f5755c2014-08-01 22:42:16 +0000138 return true;
139 }
140
141 void EmitDeferredDecls() {
Richard Smithc9cbde72014-08-13 21:15:09 +0000142 if (DeferredInlineMethodDefinitions.empty())
143 return;
144
Richard Smith1ba0a072014-08-01 20:39:36 +0000145 // Emit any deferred inline method definitions. Note that more deferred
146 // methods may be added during this loop, since ASTConsumer callbacks
147 // can be invoked if AST inspection results in declarations being added.
Richard Smithc9cbde72014-08-13 21:15:09 +0000148 HandlingTopLevelDeclRAII HandlingDecl(*this);
149 for (unsigned I = 0; I != DeferredInlineMethodDefinitions.size(); ++I)
Richard Smith1ba0a072014-08-01 20:39:36 +0000150 Builder->EmitTopLevelDecl(DeferredInlineMethodDefinitions[I]);
Richard Smith455768e2014-08-01 20:09:39 +0000151 DeferredInlineMethodDefinitions.clear();
Chris Lattneradf1f512008-02-06 02:01:47 +0000152 }
Daniel Dunbarfce4be82008-08-15 23:26:23 +0000153
Stephan Bergmann17d7d142016-03-30 06:27:31 +0000154 void HandleInlineFunctionDefinition(FunctionDecl *D) override {
Hans Wennborga926d842014-05-23 20:37:38 +0000155 if (Diags.hasErrorOccurred())
156 return;
157
158 assert(D->doesThisDeclarationHaveABody());
159
Stephan Bergmann17d7d142016-03-30 06:27:31 +0000160 // Handle friend functions.
161 if (D->isInIdentifierNamespace(Decl::IDNS_OrdinaryFriend)) {
162 if (Ctx->getTargetInfo().getCXXABI().isMicrosoft()
163 && !D->getLexicalDeclContext()->isDependentContext())
164 Builder->EmitTopLevelDecl(D);
165 return;
166 }
167
168 // Otherwise, must be a method.
169 auto MD = cast<CXXMethodDecl>(D);
170
Hans Wennborgdfcb7d62014-06-06 17:36:17 +0000171 // We may want to emit this definition. However, that decision might be
172 // based on computing the linkage, and we have to defer that in case we
173 // are inside of something that will change the method's final linkage,
174 // e.g.
175 // typedef struct {
176 // void bar();
177 // void foo() { bar(); }
178 // } A;
Stephan Bergmann17d7d142016-03-30 06:27:31 +0000179 DeferredInlineMethodDefinitions.push_back(MD);
Alex Lorenzee024992014-08-04 18:41:51 +0000180
Justin Bogner94d384e2014-11-18 00:34:46 +0000181 // Provide some coverage mapping even for methods that aren't emitted.
182 // Don't do this for templated classes though, as they may not be
183 // instantiable.
Stephan Bergmann17d7d142016-03-30 06:27:31 +0000184 if (!MD->getParent()->getDescribedClassTemplate())
185 Builder->AddDeferredUnusedCoverageMapping(MD);
Hans Wennborga926d842014-05-23 20:37:38 +0000186 }
187
Chris Lattnera5e4d302008-02-06 04:51:19 +0000188 /// HandleTagDeclDefinition - This callback is invoked each time a TagDecl
Chris Lattner5bbb3c82009-03-29 16:50:03 +0000189 /// to (e.g. struct, union, enum, class) is completed. This allows the
190 /// client hack on the type, which can occur at any point in the file
191 /// (because these can be defined in declspecs).
Craig Topper4f12f102014-03-12 06:41:41 +0000192 void HandleTagDeclDefinition(TagDecl *D) override {
David Blaikie4a9ec7b2013-08-19 21:02:26 +0000193 if (Diags.hasErrorOccurred())
194 return;
195
Reid Klecknerea53dba2016-04-22 18:46:33 +0000196 // Don't allow re-entrant calls to CodeGen triggered by PCH
197 // deserialization to emit deferred decls.
198 HandlingTopLevelDeclRAII HandlingDecl(*this, /*EmitDeferred=*/false);
199
Chris Lattner68be6062008-02-06 05:08:19 +0000200 Builder->UpdateCompletedType(D);
Hans Wennborg56fc62b2014-07-17 20:25:23 +0000201
202 // For MSVC compatibility, treat declarations of static data members with
203 // inline initializers as definitions.
David Majnemer3f021502015-10-08 04:53:31 +0000204 if (Ctx->getTargetInfo().getCXXABI().isMicrosoft()) {
Hans Wennborg56fc62b2014-07-17 20:25:23 +0000205 for (Decl *Member : D->decls()) {
206 if (VarDecl *VD = dyn_cast<VarDecl>(Member)) {
207 if (Ctx->isMSStaticDataMemberInlineDefinition(VD) &&
208 Ctx->DeclMustBeEmitted(VD)) {
209 Builder->EmitGlobal(VD);
210 }
211 }
212 }
213 }
Alexey Bataevc5b1d322016-03-04 09:22:22 +0000214 // For OpenMP emit declare reduction functions, if required.
215 if (Ctx->getLangOpts().OpenMP) {
216 for (Decl *Member : D->decls()) {
217 if (auto *DRD = dyn_cast<OMPDeclareReductionDecl>(Member)) {
218 if (Ctx->DeclMustBeEmitted(DRD))
219 Builder->EmitGlobal(DRD);
220 }
221 }
222 }
Chris Lattnera5e4d302008-02-06 04:51:19 +0000223 }
Ted Kremenek7db4f602008-08-07 19:47:41 +0000224
Craig Topper4f12f102014-03-12 06:41:41 +0000225 void HandleTagDeclRequiredDefinition(const TagDecl *D) override {
David Blaikie4a9ec7b2013-08-19 21:02:26 +0000226 if (Diags.hasErrorOccurred())
227 return;
228
Reid Klecknerea53dba2016-04-22 18:46:33 +0000229 // Don't allow re-entrant calls to CodeGen triggered by PCH
230 // deserialization to emit deferred decls.
231 HandlingTopLevelDeclRAII HandlingDecl(*this, /*EmitDeferred=*/false);
232
David Blaikie48ad6dc2013-07-13 21:08:14 +0000233 if (CodeGen::CGDebugInfo *DI = Builder->getModuleDebugInfo())
234 if (const RecordDecl *RD = dyn_cast<RecordDecl>(D))
David Blaikieb2e86eb2013-08-15 20:49:17 +0000235 DI->completeRequiredType(RD);
David Blaikie48ad6dc2013-07-13 21:08:14 +0000236 }
237
Craig Topper4f12f102014-03-12 06:41:41 +0000238 void HandleTranslationUnit(ASTContext &Ctx) override {
Manman Ren581c2b92016-01-28 23:29:02 +0000239 // Release the Builder when there is no error.
240 if (!Diags.hasErrorOccurred() && Builder)
241 Builder->Release();
242
243 // If there are errors before or when releasing the Builder, reset
244 // the module to stop here before invoking the backend.
Ted Kremenek7db4f602008-08-07 19:47:41 +0000245 if (Diags.hasErrorOccurred()) {
Rafael Espindolac0ff7442013-12-09 14:59:08 +0000246 if (Builder)
247 Builder->clear();
Ted Kremenek7db4f602008-08-07 19:47:41 +0000248 M.reset();
249 return;
250 }
Daniel Dunbare017ecc2009-12-19 17:50:07 +0000251 }
Douglas Gregorbeecd582009-04-21 17:11:58 +0000252
David Majnemer929025d2016-01-26 19:30:26 +0000253 void AssignInheritanceModel(CXXRecordDecl *RD) override {
254 if (Diags.hasErrorOccurred())
255 return;
256
257 Builder->RefreshTypeCacheForClass(RD);
258 }
259
Craig Topper4f12f102014-03-12 06:41:41 +0000260 void CompleteTentativeDefinition(VarDecl *D) override {
Douglas Gregorbeecd582009-04-21 17:11:58 +0000261 if (Diags.hasErrorOccurred())
262 return;
263
264 Builder->EmitTentativeDefinition(D);
265 }
Douglas Gregor88d292c2010-05-13 16:44:06 +0000266
Nico Weberb6a5d052015-01-15 04:07:35 +0000267 void HandleVTable(CXXRecordDecl *RD) override {
Douglas Gregor88d292c2010-05-13 16:44:06 +0000268 if (Diags.hasErrorOccurred())
269 return;
270
Nico Weberb6a5d052015-01-15 04:07:35 +0000271 Builder->EmitVTable(RD);
Douglas Gregor88d292c2010-05-13 16:44:06 +0000272 }
Chris Lattneradf1f512008-02-06 02:01:47 +0000273 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +0000274}
Chris Lattnerf97fe382007-05-24 06:29:05 +0000275
David Blaikie68e081d2011-12-20 02:48:34 +0000276void CodeGenerator::anchor() { }
277
Adrian Prantle74f5252015-06-30 02:26:03 +0000278CodeGenerator *clang::CreateLLVMCodeGen(
279 DiagnosticsEngine &Diags, const std::string &ModuleName,
280 const HeaderSearchOptions &HeaderSearchOpts,
281 const PreprocessorOptions &PreprocessorOpts, const CodeGenOptions &CGO,
282 llvm::LLVMContext &C, CoverageSourceInfo *CoverageInfo) {
283 return new CodeGeneratorImpl(Diags, ModuleName, HeaderSearchOpts,
284 PreprocessorOpts, CGO, C, CoverageInfo);
Chris Lattnerf97fe382007-05-24 06:29:05 +0000285}