1 //===--- ObjectFilePCHContainerOperations.cpp -----------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 #include "clang/CodeGen/ObjectFilePCHContainerOperations.h"
11 #include "CGDebugInfo.h"
12 #include "CodeGenModule.h"
13 #include "clang/AST/ASTContext.h"
14 #include "clang/AST/DeclObjC.h"
15 #include "clang/AST/Expr.h"
16 #include "clang/AST/RecursiveASTVisitor.h"
17 #include "clang/Basic/Diagnostic.h"
18 #include "clang/Basic/TargetInfo.h"
19 #include "clang/CodeGen/BackendUtil.h"
20 #include "clang/Frontend/CodeGenOptions.h"
21 #include "clang/Frontend/CompilerInstance.h"
22 #include "clang/Lex/Preprocessor.h"
23 #include "clang/Lex/HeaderSearch.h"
24 #include "clang/Serialization/ASTWriter.h"
25 #include "llvm/ADT/StringRef.h"
26 #include "llvm/Bitcode/BitstreamReader.h"
27 #include "llvm/DebugInfo/DWARF/DWARFContext.h"
28 #include "llvm/IR/Constants.h"
29 #include "llvm/IR/DataLayout.h"
30 #include "llvm/IR/LLVMContext.h"
31 #include "llvm/IR/Module.h"
32 #include "llvm/Object/COFF.h"
33 #include "llvm/Object/ObjectFile.h"
34 #include "llvm/Support/TargetRegistry.h"
37 using namespace clang;
39 #define DEBUG_TYPE "pchcontainer"
42 class PCHContainerGenerator : public ASTConsumer {
43 DiagnosticsEngine &Diags;
44 const std::string MainFileName;
47 const HeaderSearchOptions &HeaderSearchOpts;
48 const PreprocessorOptions &PreprocessorOpts;
49 CodeGenOptions CodeGenOpts;
50 const TargetOptions TargetOpts;
51 const LangOptions LangOpts;
52 std::unique_ptr<llvm::LLVMContext> VMContext;
53 std::unique_ptr<llvm::Module> M;
54 std::unique_ptr<CodeGen::CodeGenModule> Builder;
55 raw_pwrite_stream *OS;
56 std::shared_ptr<PCHBuffer> Buffer;
58 /// Visit every type and emit debug info for it.
59 struct DebugTypeVisitor : public RecursiveASTVisitor<DebugTypeVisitor> {
60 clang::CodeGen::CGDebugInfo &DI;
63 DebugTypeVisitor(clang::CodeGen::CGDebugInfo &DI, ASTContext &Ctx,
65 : DI(DI), Ctx(Ctx), SkipTagDecls(SkipTagDecls) {}
67 /// Determine whether this type can be represented in DWARF.
68 static bool CanRepresent(const Type *Ty) {
69 return !Ty->isDependentType() && !Ty->isUndeducedType();
72 bool VisitImportDecl(ImportDecl *D) {
73 auto *Import = cast<ImportDecl>(D);
74 if (!Import->getImportedOwningModule())
75 DI.EmitImportDecl(*Import);
79 bool VisitTypeDecl(TypeDecl *D) {
80 // TagDecls may be deferred until after all decls have been merged and we
81 // know the complete type. Pure forward declarations will be skipped, but
82 // they don't need to be emitted into the module anyway.
83 if (SkipTagDecls && isa<TagDecl>(D))
86 QualType QualTy = Ctx.getTypeDeclType(D);
87 if (!QualTy.isNull() && CanRepresent(QualTy.getTypePtr()))
88 DI.getOrCreateStandaloneType(QualTy, D->getLocation());
92 bool VisitObjCInterfaceDecl(ObjCInterfaceDecl *D) {
93 QualType QualTy(D->getTypeForDecl(), 0);
94 if (!QualTy.isNull() && CanRepresent(QualTy.getTypePtr()))
95 DI.getOrCreateStandaloneType(QualTy, D->getLocation());
99 bool VisitFunctionDecl(FunctionDecl *D) {
100 if (isa<CXXMethodDecl>(D))
101 // This is not yet supported. Constructing the `this' argument
102 // mandates a CodeGenFunction.
105 SmallVector<QualType, 16> ArgTypes;
106 for (auto i : D->params())
107 ArgTypes.push_back(i->getType());
108 QualType RetTy = D->getReturnType();
109 QualType FnTy = Ctx.getFunctionType(RetTy, ArgTypes,
110 FunctionProtoType::ExtProtoInfo());
111 if (CanRepresent(FnTy.getTypePtr()))
112 DI.EmitFunctionDecl(D, D->getLocation(), FnTy);
116 bool VisitObjCMethodDecl(ObjCMethodDecl *D) {
117 if (!D->getClassInterface())
120 bool selfIsPseudoStrong, selfIsConsumed;
121 SmallVector<QualType, 16> ArgTypes;
122 ArgTypes.push_back(D->getSelfType(Ctx, D->getClassInterface(),
123 selfIsPseudoStrong, selfIsConsumed));
124 ArgTypes.push_back(Ctx.getObjCSelType());
125 for (auto i : D->params())
126 ArgTypes.push_back(i->getType());
127 QualType RetTy = D->getReturnType();
128 QualType FnTy = Ctx.getFunctionType(RetTy, ArgTypes,
129 FunctionProtoType::ExtProtoInfo());
130 if (CanRepresent(FnTy.getTypePtr()))
131 DI.EmitFunctionDecl(D, D->getLocation(), FnTy);
137 PCHContainerGenerator(CompilerInstance &CI, const std::string &MainFileName,
138 const std::string &OutputFileName,
139 raw_pwrite_stream *OS,
140 std::shared_ptr<PCHBuffer> Buffer)
141 : Diags(CI.getDiagnostics()), Ctx(nullptr),
142 MMap(CI.getPreprocessor().getHeaderSearchInfo().getModuleMap()),
143 HeaderSearchOpts(CI.getHeaderSearchOpts()),
144 PreprocessorOpts(CI.getPreprocessorOpts()),
145 TargetOpts(CI.getTargetOpts()), LangOpts(CI.getLangOpts()), OS(OS),
147 // The debug info output isn't affected by CodeModel and
148 // ThreadModel, but the backend expects them to be nonempty.
149 CodeGenOpts.CodeModel = "default";
150 CodeGenOpts.ThreadModel = "single";
151 CodeGenOpts.DebugTypeExtRefs = true;
152 CodeGenOpts.setDebugInfo(CodeGenOptions::FullDebugInfo);
155 ~PCHContainerGenerator() override = default;
157 void Initialize(ASTContext &Context) override {
158 assert(!Ctx && "initialized multiple times");
161 VMContext.reset(new llvm::LLVMContext());
162 M.reset(new llvm::Module(MainFileName, *VMContext));
163 M->setDataLayout(Ctx->getTargetInfo().getDataLayoutString());
164 Builder.reset(new CodeGen::CodeGenModule(
165 *Ctx, HeaderSearchOpts, PreprocessorOpts, CodeGenOpts, *M, Diags));
166 Builder->getModuleDebugInfo()->setModuleMap(MMap);
169 bool HandleTopLevelDecl(DeclGroupRef D) override {
170 if (Diags.hasErrorOccurred())
173 // Collect debug info for all decls in this group.
175 if (!I->isFromASTFile()) {
176 DebugTypeVisitor DTV(*Builder->getModuleDebugInfo(), *Ctx, true);
182 void HandleTopLevelDeclInObjCContainer(DeclGroupRef D) override {
183 HandleTopLevelDecl(D);
186 void HandleTagDeclDefinition(TagDecl *D) override {
187 if (Diags.hasErrorOccurred())
190 if (D->isFromASTFile())
193 DebugTypeVisitor DTV(*Builder->getModuleDebugInfo(), *Ctx, false);
195 Builder->UpdateCompletedType(D);
198 void HandleTagDeclRequiredDefinition(const TagDecl *D) override {
199 if (Diags.hasErrorOccurred())
202 if (const RecordDecl *RD = dyn_cast<RecordDecl>(D))
203 Builder->getModuleDebugInfo()->completeRequiredType(RD);
206 /// Emit a container holding the serialized AST.
207 void HandleTranslationUnit(ASTContext &Ctx) override {
208 assert(M && VMContext && Builder);
209 // Delete these on function exit.
210 std::unique_ptr<llvm::LLVMContext> VMContext = std::move(this->VMContext);
211 std::unique_ptr<llvm::Module> M = std::move(this->M);
212 std::unique_ptr<CodeGen::CodeGenModule> Builder = std::move(this->Builder);
214 if (Diags.hasErrorOccurred())
217 M->setTargetTriple(Ctx.getTargetInfo().getTriple().getTriple());
218 M->setDataLayout(Ctx.getTargetInfo().getDataLayoutString());
219 Builder->getModuleDebugInfo()->setDwoId(Buffer->Signature);
221 // Finalize the Builder.
225 // Ensure the target exists.
227 auto Triple = Ctx.getTargetInfo().getTriple();
228 if (!llvm::TargetRegistry::lookupTarget(Triple.getTriple(), Error))
229 llvm::report_fatal_error(Error);
231 // Emit the serialized Clang AST into its own section.
232 assert(Buffer->IsComplete && "serialization did not complete");
233 auto &SerializedAST = Buffer->Data;
234 auto Size = SerializedAST.size();
235 auto Int8Ty = llvm::Type::getInt8Ty(*VMContext);
236 auto *Ty = llvm::ArrayType::get(Int8Ty, Size);
237 auto *Data = llvm::ConstantDataArray::getString(
238 *VMContext, StringRef(SerializedAST.data(), Size),
240 auto *ASTSym = new llvm::GlobalVariable(
241 *M, Ty, /*constant*/ true, llvm::GlobalVariable::InternalLinkage, Data,
243 // The on-disk hashtable needs to be aligned.
244 ASTSym->setAlignment(8);
246 // Mach-O also needs a segment name.
247 if (Triple.isOSBinFormatMachO())
248 ASTSym->setSection("__CLANG,__clangast");
249 // COFF has an eight character length limit.
250 else if (Triple.isOSBinFormatCOFF())
251 ASTSym->setSection("clangast");
253 ASTSym->setSection("__clangast");
256 // Print the IR for the PCH container to the debug output.
257 llvm::SmallString<0> Buffer;
258 llvm::raw_svector_ostream OS(Buffer);
259 clang::EmitBackendOutput(Diags, CodeGenOpts, TargetOpts, LangOpts,
260 Ctx.getTargetInfo().getDataLayoutString(),
261 M.get(), BackendAction::Backend_EmitLL, &OS);
262 llvm::dbgs() << Buffer;
265 // Use the LLVM backend to emit the pch container.
266 clang::EmitBackendOutput(Diags, CodeGenOpts, TargetOpts, LangOpts,
267 Ctx.getTargetInfo().getDataLayoutString(),
268 M.get(), BackendAction::Backend_EmitObj, OS);
270 // Make sure the pch container hits disk.
273 // Free the memory for the temporary buffer.
274 llvm::SmallVector<char, 0> Empty;
275 SerializedAST = std::move(Empty);
279 } // anonymous namespace
281 std::unique_ptr<ASTConsumer>
282 ObjectFilePCHContainerWriter::CreatePCHContainerGenerator(
283 CompilerInstance &CI, const std::string &MainFileName,
284 const std::string &OutputFileName, llvm::raw_pwrite_stream *OS,
285 std::shared_ptr<PCHBuffer> Buffer) const {
286 return llvm::make_unique<PCHContainerGenerator>(CI, MainFileName,
287 OutputFileName, OS, Buffer);
290 void ObjectFilePCHContainerReader::ExtractPCH(
291 llvm::MemoryBufferRef Buffer, llvm::BitstreamReader &StreamFile) const {
292 if (auto OF = llvm::object::ObjectFile::createObjectFile(Buffer)) {
293 auto *Obj = OF.get().get();
294 bool IsCOFF = isa<llvm::object::COFFObjectFile>(Obj);
295 // Find the clang AST section in the container.
296 for (auto &Section : OF->get()->sections()) {
298 Section.getName(Name);
299 if ((!IsCOFF && Name == "__clangast") ||
300 ( IsCOFF && Name == "clangast")) {
302 Section.getContents(Buf);
303 StreamFile.init((const unsigned char *)Buf.begin(),
304 (const unsigned char *)Buf.end());
310 // As a fallback, treat the buffer as a raw AST.
311 StreamFile.init((const unsigned char *)Buffer.getBufferStart(),
312 (const unsigned char *)Buffer.getBufferEnd());