1 //===--- ObjectFilePCHContainerWriter.cpp -----------------------------===//
3 // 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
7 //===----------------------------------------------------------------------===//
9 #include "clang/CodeGen/ObjectFilePCHContainerWriter.h"
10 #include "CGDebugInfo.h"
11 #include "CodeGenModule.h"
12 #include "clang/AST/ASTContext.h"
13 #include "clang/AST/DeclObjC.h"
14 #include "clang/AST/Expr.h"
15 #include "clang/AST/RecursiveASTVisitor.h"
16 #include "clang/Basic/CodeGenOptions.h"
17 #include "clang/Basic/Diagnostic.h"
18 #include "clang/Basic/TargetInfo.h"
19 #include "clang/CodeGen/BackendUtil.h"
20 #include "clang/Frontend/CompilerInstance.h"
21 #include "clang/Lex/HeaderSearch.h"
22 #include "clang/Lex/Preprocessor.h"
23 #include "llvm/ADT/StringRef.h"
24 #include "llvm/IR/Constants.h"
25 #include "llvm/IR/DataLayout.h"
26 #include "llvm/IR/LLVMContext.h"
27 #include "llvm/IR/Module.h"
28 #include "llvm/MC/TargetRegistry.h"
29 #include "llvm/Object/COFF.h"
30 #include "llvm/Support/Path.h"
34 using namespace clang
;
36 #define DEBUG_TYPE "pchcontainer"
39 class PCHContainerGenerator
: public ASTConsumer
{
40 DiagnosticsEngine
&Diags
;
41 const std::string MainFileName
;
42 const std::string OutputFileName
;
45 IntrusiveRefCntPtr
<llvm::vfs::FileSystem
> FS
;
46 const HeaderSearchOptions
&HeaderSearchOpts
;
47 const PreprocessorOptions
&PreprocessorOpts
;
48 CodeGenOptions CodeGenOpts
;
49 const TargetOptions TargetOpts
;
51 std::unique_ptr
<llvm::LLVMContext
> VMContext
;
52 std::unique_ptr
<llvm::Module
> M
;
53 std::unique_ptr
<CodeGen::CodeGenModule
> Builder
;
54 std::unique_ptr
<raw_pwrite_stream
> OS
;
55 std::shared_ptr
<PCHBuffer
> Buffer
;
57 /// Visit every type and emit debug info for it.
58 struct DebugTypeVisitor
: public RecursiveASTVisitor
<DebugTypeVisitor
> {
59 clang::CodeGen::CGDebugInfo
&DI
;
61 DebugTypeVisitor(clang::CodeGen::CGDebugInfo
&DI
, ASTContext
&Ctx
)
64 /// Determine whether this type can be represented in DWARF.
65 static bool CanRepresent(const Type
*Ty
) {
66 return !Ty
->isDependentType() && !Ty
->isUndeducedType();
69 bool VisitImportDecl(ImportDecl
*D
) {
70 if (!D
->getImportedOwningModule())
71 DI
.EmitImportDecl(*D
);
75 bool VisitTypeDecl(TypeDecl
*D
) {
76 // TagDecls may be deferred until after all decls have been merged and we
77 // know the complete type. Pure forward declarations will be skipped, but
78 // they don't need to be emitted into the module anyway.
79 if (auto *TD
= dyn_cast
<TagDecl
>(D
))
80 if (!TD
->isCompleteDefinition())
83 QualType QualTy
= Ctx
.getTypeDeclType(D
);
84 if (!QualTy
.isNull() && CanRepresent(QualTy
.getTypePtr()))
85 DI
.getOrCreateStandaloneType(QualTy
, D
->getLocation());
89 bool VisitObjCInterfaceDecl(ObjCInterfaceDecl
*D
) {
90 QualType
QualTy(D
->getTypeForDecl(), 0);
91 if (!QualTy
.isNull() && CanRepresent(QualTy
.getTypePtr()))
92 DI
.getOrCreateStandaloneType(QualTy
, D
->getLocation());
96 bool VisitFunctionDecl(FunctionDecl
*D
) {
97 // Skip deduction guides.
98 if (isa
<CXXDeductionGuideDecl
>(D
))
101 if (isa
<CXXMethodDecl
>(D
))
102 // This is not yet supported. Constructing the `this' argument
103 // mandates a CodeGenFunction.
106 SmallVector
<QualType
, 16> ArgTypes
;
107 for (auto *i
: D
->parameters())
108 ArgTypes
.push_back(i
->getType());
109 QualType RetTy
= D
->getReturnType();
110 QualType FnTy
= Ctx
.getFunctionType(RetTy
, ArgTypes
,
111 FunctionProtoType::ExtProtoInfo());
112 if (CanRepresent(FnTy
.getTypePtr()))
113 DI
.EmitFunctionDecl(D
, D
->getLocation(), FnTy
);
117 bool VisitObjCMethodDecl(ObjCMethodDecl
*D
) {
118 if (!D
->getClassInterface())
121 bool selfIsPseudoStrong
, selfIsConsumed
;
122 SmallVector
<QualType
, 16> ArgTypes
;
123 ArgTypes
.push_back(D
->getSelfType(Ctx
, D
->getClassInterface(),
124 selfIsPseudoStrong
, selfIsConsumed
));
125 ArgTypes
.push_back(Ctx
.getObjCSelType());
126 for (auto *i
: D
->parameters())
127 ArgTypes
.push_back(i
->getType());
128 QualType RetTy
= D
->getReturnType();
129 QualType FnTy
= Ctx
.getFunctionType(RetTy
, ArgTypes
,
130 FunctionProtoType::ExtProtoInfo());
131 if (CanRepresent(FnTy
.getTypePtr()))
132 DI
.EmitFunctionDecl(D
, D
->getLocation(), FnTy
);
138 PCHContainerGenerator(CompilerInstance
&CI
, const std::string
&MainFileName
,
139 const std::string
&OutputFileName
,
140 std::unique_ptr
<raw_pwrite_stream
> OS
,
141 std::shared_ptr
<PCHBuffer
> Buffer
)
142 : Diags(CI
.getDiagnostics()), MainFileName(MainFileName
),
143 OutputFileName(OutputFileName
), Ctx(nullptr),
144 MMap(CI
.getPreprocessor().getHeaderSearchInfo().getModuleMap()),
145 FS(&CI
.getVirtualFileSystem()),
146 HeaderSearchOpts(CI
.getHeaderSearchOpts()),
147 PreprocessorOpts(CI
.getPreprocessorOpts()),
148 TargetOpts(CI
.getTargetOpts()), LangOpts(CI
.getLangOpts()),
149 OS(std::move(OS
)), Buffer(std::move(Buffer
)) {
150 // The debug info output isn't affected by CodeModel and
151 // ThreadModel, but the backend expects them to be nonempty.
152 CodeGenOpts
.CodeModel
= "default";
153 LangOpts
.setThreadModel(LangOptions::ThreadModelKind::Single
);
154 CodeGenOpts
.DebugTypeExtRefs
= true;
155 // When building a module MainFileName is the name of the modulemap file.
156 CodeGenOpts
.MainFileName
=
157 LangOpts
.CurrentModule
.empty() ? MainFileName
: LangOpts
.CurrentModule
;
158 CodeGenOpts
.setDebugInfo(llvm::codegenoptions::FullDebugInfo
);
159 CodeGenOpts
.setDebuggerTuning(CI
.getCodeGenOpts().getDebuggerTuning());
160 CodeGenOpts
.DwarfVersion
= CI
.getCodeGenOpts().DwarfVersion
;
161 CodeGenOpts
.DebugCompilationDir
=
162 CI
.getInvocation().getCodeGenOpts().DebugCompilationDir
;
163 CodeGenOpts
.DebugPrefixMap
=
164 CI
.getInvocation().getCodeGenOpts().DebugPrefixMap
;
165 CodeGenOpts
.DebugStrictDwarf
= CI
.getCodeGenOpts().DebugStrictDwarf
;
168 ~PCHContainerGenerator() override
= default;
170 void Initialize(ASTContext
&Context
) override
{
171 assert(!Ctx
&& "initialized multiple times");
174 VMContext
.reset(new llvm::LLVMContext());
175 M
.reset(new llvm::Module(MainFileName
, *VMContext
));
176 M
->setDataLayout(Ctx
->getTargetInfo().getDataLayoutString());
177 Builder
.reset(new CodeGen::CodeGenModule(
178 *Ctx
, FS
, HeaderSearchOpts
, PreprocessorOpts
, CodeGenOpts
, *M
, Diags
));
180 // Prepare CGDebugInfo to emit debug info for a clang module.
181 auto *DI
= Builder
->getModuleDebugInfo();
182 StringRef ModuleName
= llvm::sys::path::filename(MainFileName
);
183 DI
->setPCHDescriptor(
184 {ModuleName
, "", OutputFileName
, ASTFileSignature::createDISentinel()});
185 DI
->setModuleMap(MMap
);
188 bool HandleTopLevelDecl(DeclGroupRef D
) override
{
189 if (Diags
.hasErrorOccurred())
192 // Collect debug info for all decls in this group.
194 if (!I
->isFromASTFile()) {
195 DebugTypeVisitor
DTV(*Builder
->getModuleDebugInfo(), *Ctx
);
201 void HandleTopLevelDeclInObjCContainer(DeclGroupRef D
) override
{
202 HandleTopLevelDecl(D
);
205 void HandleTagDeclDefinition(TagDecl
*D
) override
{
206 if (Diags
.hasErrorOccurred())
209 if (D
->isFromASTFile())
212 // Anonymous tag decls are deferred until we are building their declcontext.
213 if (D
->getName().empty())
216 // Defer tag decls until their declcontext is complete.
217 auto *DeclCtx
= D
->getDeclContext();
219 if (auto *D
= dyn_cast
<TagDecl
>(DeclCtx
))
220 if (!D
->isCompleteDefinition())
222 DeclCtx
= DeclCtx
->getParent();
225 DebugTypeVisitor
DTV(*Builder
->getModuleDebugInfo(), *Ctx
);
227 Builder
->UpdateCompletedType(D
);
230 void HandleTagDeclRequiredDefinition(const TagDecl
*D
) override
{
231 if (Diags
.hasErrorOccurred())
234 if (const RecordDecl
*RD
= dyn_cast
<RecordDecl
>(D
))
235 Builder
->getModuleDebugInfo()->completeRequiredType(RD
);
238 void HandleImplicitImportDecl(ImportDecl
*D
) override
{
239 if (!D
->getImportedOwningModule())
240 Builder
->getModuleDebugInfo()->EmitImportDecl(*D
);
243 /// Emit a container holding the serialized AST.
244 void HandleTranslationUnit(ASTContext
&Ctx
) override
{
245 assert(M
&& VMContext
&& Builder
);
246 // Delete these on function exit.
247 std::unique_ptr
<llvm::LLVMContext
> VMContext
= std::move(this->VMContext
);
248 std::unique_ptr
<llvm::Module
> M
= std::move(this->M
);
249 std::unique_ptr
<CodeGen::CodeGenModule
> Builder
= std::move(this->Builder
);
251 if (Diags
.hasErrorOccurred())
254 M
->setTargetTriple(Ctx
.getTargetInfo().getTriple().getTriple());
255 M
->setDataLayout(Ctx
.getTargetInfo().getDataLayoutString());
257 // PCH files don't have a signature field in the control block,
258 // but LLVM detects DWO CUs by looking for a non-zero DWO id.
259 // We use the lower 64 bits for debug info.
262 Buffer
->Signature
? Buffer
->Signature
.truncatedValue() : ~1ULL;
264 Builder
->getModuleDebugInfo()->setDwoId(Signature
);
266 // Finalize the Builder.
270 // Ensure the target exists.
272 auto Triple
= Ctx
.getTargetInfo().getTriple();
273 if (!llvm::TargetRegistry::lookupTarget(Triple
.getTriple(), Error
))
274 llvm::report_fatal_error(llvm::Twine(Error
));
276 // Emit the serialized Clang AST into its own section.
277 assert(Buffer
->IsComplete
&& "serialization did not complete");
278 auto &SerializedAST
= Buffer
->Data
;
279 auto Size
= SerializedAST
.size();
281 if (Triple
.isOSBinFormatWasm()) {
282 // Emit __clangast in custom section instead of named data segment
283 // to find it while iterating sections.
284 // This could be avoided if all data segements (the wasm sense) were
285 // represented as their own sections (in the llvm sense).
286 // TODO: https://github.com/WebAssembly/tool-conventions/issues/138
287 llvm::NamedMDNode
*MD
=
288 M
->getOrInsertNamedMetadata("wasm.custom_sections");
289 llvm::Metadata
*Ops
[2] = {
290 llvm::MDString::get(*VMContext
, "__clangast"),
291 llvm::MDString::get(*VMContext
,
292 StringRef(SerializedAST
.data(), Size
))};
293 auto *NameAndContent
= llvm::MDTuple::get(*VMContext
, Ops
);
294 MD
->addOperand(NameAndContent
);
296 auto Int8Ty
= llvm::Type::getInt8Ty(*VMContext
);
297 auto *Ty
= llvm::ArrayType::get(Int8Ty
, Size
);
298 auto *Data
= llvm::ConstantDataArray::getString(
299 *VMContext
, StringRef(SerializedAST
.data(), Size
),
301 auto *ASTSym
= new llvm::GlobalVariable(
302 *M
, Ty
, /*constant*/ true, llvm::GlobalVariable::InternalLinkage
,
303 Data
, "__clang_ast");
304 // The on-disk hashtable needs to be aligned.
305 ASTSym
->setAlignment(llvm::Align(8));
307 // Mach-O also needs a segment name.
308 if (Triple
.isOSBinFormatMachO())
309 ASTSym
->setSection("__CLANG,__clangast");
310 // COFF has an eight character length limit.
311 else if (Triple
.isOSBinFormatCOFF())
312 ASTSym
->setSection("clangast");
314 ASTSym
->setSection("__clangast");
318 // Print the IR for the PCH container to the debug output.
319 llvm::SmallString
<0> Buffer
;
320 clang::EmitBackendOutput(
321 Diags
, HeaderSearchOpts
, CodeGenOpts
, TargetOpts
, LangOpts
,
322 Ctx
.getTargetInfo().getDataLayoutString(), M
.get(),
323 BackendAction::Backend_EmitLL
, FS
,
324 std::make_unique
<llvm::raw_svector_ostream
>(Buffer
));
325 llvm::dbgs() << Buffer
;
328 // Use the LLVM backend to emit the pch container.
329 clang::EmitBackendOutput(Diags
, HeaderSearchOpts
, CodeGenOpts
, TargetOpts
,
331 Ctx
.getTargetInfo().getDataLayoutString(), M
.get(),
332 BackendAction::Backend_EmitObj
, FS
, std::move(OS
));
334 // Free the memory for the temporary buffer.
335 llvm::SmallVector
<char, 0> Empty
;
336 SerializedAST
= std::move(Empty
);
340 } // anonymous namespace
342 std::unique_ptr
<ASTConsumer
>
343 ObjectFilePCHContainerWriter::CreatePCHContainerGenerator(
344 CompilerInstance
&CI
, const std::string
&MainFileName
,
345 const std::string
&OutputFileName
,
346 std::unique_ptr
<llvm::raw_pwrite_stream
> OS
,
347 std::shared_ptr
<PCHBuffer
> Buffer
) const {
348 return std::make_unique
<PCHContainerGenerator
>(
349 CI
, MainFileName
, OutputFileName
, std::move(OS
), Buffer
);