1bc068586SAdrian Prantl //===--- ObjectFilePCHContainerOperations.cpp -----------------------------===//
2bc068586SAdrian Prantl //
32946cd70SChandler Carruth // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
42946cd70SChandler Carruth // See https://llvm.org/LICENSE.txt for license information.
52946cd70SChandler Carruth // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6bc068586SAdrian Prantl //
7bc068586SAdrian Prantl //===----------------------------------------------------------------------===//
8bc068586SAdrian Prantl 
9bc068586SAdrian Prantl #include "clang/CodeGen/ObjectFilePCHContainerOperations.h"
10bc068586SAdrian Prantl #include "CGDebugInfo.h"
11bc068586SAdrian Prantl #include "CodeGenModule.h"
12bc068586SAdrian Prantl #include "clang/AST/ASTContext.h"
13bc068586SAdrian Prantl #include "clang/AST/DeclObjC.h"
14bc068586SAdrian Prantl #include "clang/AST/Expr.h"
15bc068586SAdrian Prantl #include "clang/AST/RecursiveASTVisitor.h"
166368818fSRichard Trieu #include "clang/Basic/CodeGenOptions.h"
17bc068586SAdrian Prantl #include "clang/Basic/Diagnostic.h"
18bc068586SAdrian Prantl #include "clang/Basic/TargetInfo.h"
19bc068586SAdrian Prantl #include "clang/CodeGen/BackendUtil.h"
200391406eSAdrian Prantl #include "clang/Frontend/CompilerInstance.h"
219402cef0SAdrian Prantl #include "clang/Lex/HeaderSearch.h"
223a2d4947SAdrian Prantl #include "clang/Lex/Preprocessor.h"
23bc068586SAdrian Prantl #include "llvm/ADT/StringRef.h"
24e0308279SFrancis Visoiu Mistrih #include "llvm/Bitstream/BitstreamReader.h"
25bc068586SAdrian Prantl #include "llvm/DebugInfo/DWARF/DWARFContext.h"
26bc068586SAdrian Prantl #include "llvm/IR/Constants.h"
27bc068586SAdrian Prantl #include "llvm/IR/DataLayout.h"
28bc068586SAdrian Prantl #include "llvm/IR/LLVMContext.h"
29bc068586SAdrian Prantl #include "llvm/IR/Module.h"
30bc068586SAdrian Prantl #include "llvm/Object/COFF.h"
31bc068586SAdrian Prantl #include "llvm/Object/ObjectFile.h"
323a2d4947SAdrian Prantl #include "llvm/Support/Path.h"
33bc068586SAdrian Prantl #include "llvm/Support/TargetRegistry.h"
34bc068586SAdrian Prantl #include <memory>
35cfeacf56SBenjamin Kramer #include <utility>
367eb5464bSHans Wennborg 
37bc068586SAdrian Prantl using namespace clang;
38bc068586SAdrian Prantl 
39bc068586SAdrian Prantl #define DEBUG_TYPE "pchcontainer"
40bc068586SAdrian Prantl 
41bc068586SAdrian Prantl namespace {
425a88e1a8SAdrian Prantl class PCHContainerGenerator : public ASTConsumer {
43bc068586SAdrian Prantl   DiagnosticsEngine &Diags;
44bc068586SAdrian Prantl   const std::string MainFileName;
45aa5d08d0SAdrian Prantl   const std::string OutputFileName;
46bc068586SAdrian Prantl   ASTContext *Ctx;
479402cef0SAdrian Prantl   ModuleMap &MMap;
48bc068586SAdrian Prantl   const HeaderSearchOptions &HeaderSearchOpts;
49bc068586SAdrian Prantl   const PreprocessorOptions &PreprocessorOpts;
50bc068586SAdrian Prantl   CodeGenOptions CodeGenOpts;
51bc068586SAdrian Prantl   const TargetOptions TargetOpts;
52bc068586SAdrian Prantl   const LangOptions LangOpts;
53bc068586SAdrian Prantl   std::unique_ptr<llvm::LLVMContext> VMContext;
54bc068586SAdrian Prantl   std::unique_ptr<llvm::Module> M;
55bc068586SAdrian Prantl   std::unique_ptr<CodeGen::CodeGenModule> Builder;
5603f8907fSPeter Collingbourne   std::unique_ptr<raw_pwrite_stream> OS;
57bc068586SAdrian Prantl   std::shared_ptr<PCHBuffer> Buffer;
58bc068586SAdrian Prantl 
594aa2b3a3SAdrian Prantl   /// Visit every type and emit debug info for it.
604aa2b3a3SAdrian Prantl   struct DebugTypeVisitor : public RecursiveASTVisitor<DebugTypeVisitor> {
614aa2b3a3SAdrian Prantl     clang::CodeGen::CGDebugInfo &DI;
624aa2b3a3SAdrian Prantl     ASTContext &Ctx;
63cd975018SAdrian Prantl     DebugTypeVisitor(clang::CodeGen::CGDebugInfo &DI, ASTContext &Ctx)
64cd975018SAdrian Prantl         : DI(DI), Ctx(Ctx) {}
654aa2b3a3SAdrian Prantl 
664aa2b3a3SAdrian Prantl     /// Determine whether this type can be represented in DWARF.
674aa2b3a3SAdrian Prantl     static bool CanRepresent(const Type *Ty) {
684aa2b3a3SAdrian Prantl       return !Ty->isDependentType() && !Ty->isUndeducedType();
694aa2b3a3SAdrian Prantl     }
704aa2b3a3SAdrian Prantl 
7185d938aaSAdrian Prantl     bool VisitImportDecl(ImportDecl *D) {
721b88acedSAdrian Prantl       if (!D->getImportedOwningModule())
731b88acedSAdrian Prantl         DI.EmitImportDecl(*D);
7485d938aaSAdrian Prantl       return true;
7585d938aaSAdrian Prantl     }
7685d938aaSAdrian Prantl 
774aa2b3a3SAdrian Prantl     bool VisitTypeDecl(TypeDecl *D) {
78b3b821f1SAdrian Prantl       // TagDecls may be deferred until after all decls have been merged and we
79b3b821f1SAdrian Prantl       // know the complete type. Pure forward declarations will be skipped, but
80b3b821f1SAdrian Prantl       // they don't need to be emitted into the module anyway.
81cd975018SAdrian Prantl       if (auto *TD = dyn_cast<TagDecl>(D))
82cd975018SAdrian Prantl         if (!TD->isCompleteDefinition())
83b3b821f1SAdrian Prantl           return true;
84b3b821f1SAdrian Prantl 
854aa2b3a3SAdrian Prantl       QualType QualTy = Ctx.getTypeDeclType(D);
864aa2b3a3SAdrian Prantl       if (!QualTy.isNull() && CanRepresent(QualTy.getTypePtr()))
874aa2b3a3SAdrian Prantl         DI.getOrCreateStandaloneType(QualTy, D->getLocation());
884aa2b3a3SAdrian Prantl       return true;
894aa2b3a3SAdrian Prantl     }
904aa2b3a3SAdrian Prantl 
91748a6cd1SAdrian Prantl     bool VisitObjCInterfaceDecl(ObjCInterfaceDecl *D) {
92748a6cd1SAdrian Prantl       QualType QualTy(D->getTypeForDecl(), 0);
93748a6cd1SAdrian Prantl       if (!QualTy.isNull() && CanRepresent(QualTy.getTypePtr()))
94748a6cd1SAdrian Prantl         DI.getOrCreateStandaloneType(QualTy, D->getLocation());
95748a6cd1SAdrian Prantl       return true;
96748a6cd1SAdrian Prantl     }
97748a6cd1SAdrian Prantl 
98748a6cd1SAdrian Prantl     bool VisitFunctionDecl(FunctionDecl *D) {
99748a6cd1SAdrian Prantl       if (isa<CXXMethodDecl>(D))
100748a6cd1SAdrian Prantl         // This is not yet supported. Constructing the `this' argument
101748a6cd1SAdrian Prantl         // mandates a CodeGenFunction.
102748a6cd1SAdrian Prantl         return true;
103748a6cd1SAdrian Prantl 
104748a6cd1SAdrian Prantl       SmallVector<QualType, 16> ArgTypes;
10559f77921SDavid Majnemer       for (auto i : D->parameters())
106748a6cd1SAdrian Prantl         ArgTypes.push_back(i->getType());
107748a6cd1SAdrian Prantl       QualType RetTy = D->getReturnType();
108748a6cd1SAdrian Prantl       QualType FnTy = Ctx.getFunctionType(RetTy, ArgTypes,
109748a6cd1SAdrian Prantl                                           FunctionProtoType::ExtProtoInfo());
110748a6cd1SAdrian Prantl       if (CanRepresent(FnTy.getTypePtr()))
111748a6cd1SAdrian Prantl         DI.EmitFunctionDecl(D, D->getLocation(), FnTy);
112748a6cd1SAdrian Prantl       return true;
113748a6cd1SAdrian Prantl     }
114748a6cd1SAdrian Prantl 
115748a6cd1SAdrian Prantl     bool VisitObjCMethodDecl(ObjCMethodDecl *D) {
116748a6cd1SAdrian Prantl       if (!D->getClassInterface())
117748a6cd1SAdrian Prantl         return true;
118748a6cd1SAdrian Prantl 
119748a6cd1SAdrian Prantl       bool selfIsPseudoStrong, selfIsConsumed;
120748a6cd1SAdrian Prantl       SmallVector<QualType, 16> ArgTypes;
121748a6cd1SAdrian Prantl       ArgTypes.push_back(D->getSelfType(Ctx, D->getClassInterface(),
122748a6cd1SAdrian Prantl                                         selfIsPseudoStrong, selfIsConsumed));
123748a6cd1SAdrian Prantl       ArgTypes.push_back(Ctx.getObjCSelType());
12459f77921SDavid Majnemer       for (auto i : D->parameters())
125748a6cd1SAdrian Prantl         ArgTypes.push_back(i->getType());
126748a6cd1SAdrian Prantl       QualType RetTy = D->getReturnType();
127748a6cd1SAdrian Prantl       QualType FnTy = Ctx.getFunctionType(RetTy, ArgTypes,
128748a6cd1SAdrian Prantl                                           FunctionProtoType::ExtProtoInfo());
129748a6cd1SAdrian Prantl       if (CanRepresent(FnTy.getTypePtr()))
130748a6cd1SAdrian Prantl         DI.EmitFunctionDecl(D, D->getLocation(), FnTy);
131748a6cd1SAdrian Prantl       return true;
132748a6cd1SAdrian Prantl     }
1334aa2b3a3SAdrian Prantl   };
1344aa2b3a3SAdrian Prantl 
135bc068586SAdrian Prantl public:
1361e63b2bdSAdrian Prantl   PCHContainerGenerator(CompilerInstance &CI, const std::string &MainFileName,
1375a88e1a8SAdrian Prantl                         const std::string &OutputFileName,
13803f8907fSPeter Collingbourne                         std::unique_ptr<raw_pwrite_stream> OS,
1395a88e1a8SAdrian Prantl                         std::shared_ptr<PCHBuffer> Buffer)
140aa5d08d0SAdrian Prantl       : Diags(CI.getDiagnostics()), MainFileName(MainFileName),
141aa5d08d0SAdrian Prantl         OutputFileName(OutputFileName), Ctx(nullptr),
1429402cef0SAdrian Prantl         MMap(CI.getPreprocessor().getHeaderSearchInfo().getModuleMap()),
1431e63b2bdSAdrian Prantl         HeaderSearchOpts(CI.getHeaderSearchOpts()),
1440391406eSAdrian Prantl         PreprocessorOpts(CI.getPreprocessorOpts()),
14503f8907fSPeter Collingbourne         TargetOpts(CI.getTargetOpts()), LangOpts(CI.getLangOpts()),
14603f8907fSPeter Collingbourne         OS(std::move(OS)), Buffer(std::move(Buffer)) {
147bc068586SAdrian Prantl     // The debug info output isn't affected by CodeModel and
148bc068586SAdrian Prantl     // ThreadModel, but the backend expects them to be nonempty.
149bc068586SAdrian Prantl     CodeGenOpts.CodeModel = "default";
150bc068586SAdrian Prantl     CodeGenOpts.ThreadModel = "single";
1516b21ab21SAdrian Prantl     CodeGenOpts.DebugTypeExtRefs = true;
1529a1a1aa2SAdrian Prantl     // When building a module MainFileName is the name of the modulemap file.
1539a1a1aa2SAdrian Prantl     CodeGenOpts.MainFileName =
1549a1a1aa2SAdrian Prantl         LangOpts.CurrentModule.empty() ? MainFileName : LangOpts.CurrentModule;
1558c30592eSBenjamin Kramer     CodeGenOpts.setDebugInfo(codegenoptions::FullDebugInfo);
156af09f4acSDavid Blaikie     CodeGenOpts.setDebuggerTuning(CI.getCodeGenOpts().getDebuggerTuning());
15755fcb4e9SAdrian Prantl     CodeGenOpts.DebugPrefixMap =
15855fcb4e9SAdrian Prantl         CI.getInvocation().getCodeGenOpts().DebugPrefixMap;
159bc068586SAdrian Prantl   }
160bc068586SAdrian Prantl 
1617eb5464bSHans Wennborg   ~PCHContainerGenerator() override = default;
162bc068586SAdrian Prantl 
163bc068586SAdrian Prantl   void Initialize(ASTContext &Context) override {
164293534b1SRichard Smith     assert(!Ctx && "initialized multiple times");
1650f99d6a4SRichard Smith 
166bc068586SAdrian Prantl     Ctx = &Context;
167bc068586SAdrian Prantl     VMContext.reset(new llvm::LLVMContext());
168bc068586SAdrian Prantl     M.reset(new llvm::Module(MainFileName, *VMContext));
169b214cbc7SJames Y Knight     M->setDataLayout(Ctx->getTargetInfo().getDataLayout());
170ca3cf9e6SMehdi Amini     Builder.reset(new CodeGen::CodeGenModule(
171ca3cf9e6SMehdi Amini         *Ctx, HeaderSearchOpts, PreprocessorOpts, CodeGenOpts, *M, Diags));
1723a2d4947SAdrian Prantl 
1733a2d4947SAdrian Prantl     // Prepare CGDebugInfo to emit debug info for a clang module.
1743a2d4947SAdrian Prantl     auto *DI = Builder->getModuleDebugInfo();
1753a2d4947SAdrian Prantl     StringRef ModuleName = llvm::sys::path::filename(MainFileName);
176e87e55edSDaniel Grumberg     DI->setPCHDescriptor(
177e87e55edSDaniel Grumberg         {ModuleName, "", OutputFileName, ASTFileSignature::createDISentinel()});
1783a2d4947SAdrian Prantl     DI->setModuleMap(MMap);
179bc068586SAdrian Prantl   }
180bc068586SAdrian Prantl 
1814aa2b3a3SAdrian Prantl   bool HandleTopLevelDecl(DeclGroupRef D) override {
182abdd6fc4SAdrian Prantl     if (Diags.hasErrorOccurred())
1834aa2b3a3SAdrian Prantl       return true;
1844aa2b3a3SAdrian Prantl 
1854aa2b3a3SAdrian Prantl     // Collect debug info for all decls in this group.
1864aa2b3a3SAdrian Prantl     for (auto *I : D)
1874aa2b3a3SAdrian Prantl       if (!I->isFromASTFile()) {
188cd975018SAdrian Prantl         DebugTypeVisitor DTV(*Builder->getModuleDebugInfo(), *Ctx);
1894aa2b3a3SAdrian Prantl         DTV.TraverseDecl(I);
1904aa2b3a3SAdrian Prantl       }
1914aa2b3a3SAdrian Prantl     return true;
1924aa2b3a3SAdrian Prantl   }
1934aa2b3a3SAdrian Prantl 
194d43fe0bdSAdrian Prantl   void HandleTopLevelDeclInObjCContainer(DeclGroupRef D) override {
195d43fe0bdSAdrian Prantl     HandleTopLevelDecl(D);
196d43fe0bdSAdrian Prantl   }
197d43fe0bdSAdrian Prantl 
1984aa2b3a3SAdrian Prantl   void HandleTagDeclDefinition(TagDecl *D) override {
1994aa2b3a3SAdrian Prantl     if (Diags.hasErrorOccurred())
2004aa2b3a3SAdrian Prantl       return;
2014aa2b3a3SAdrian Prantl 
202b3b821f1SAdrian Prantl     if (D->isFromASTFile())
203b3b821f1SAdrian Prantl       return;
204b3b821f1SAdrian Prantl 
205e5238d2aSAdrian Prantl     // Anonymous tag decls are deferred until we are building their declcontext.
206e5238d2aSAdrian Prantl     if (D->getName().empty())
207e5238d2aSAdrian Prantl       return;
208e5238d2aSAdrian Prantl 
2095a9a4277SAdrian Prantl     // Defer tag decls until their declcontext is complete.
2105a9a4277SAdrian Prantl     auto *DeclCtx = D->getDeclContext();
2115a9a4277SAdrian Prantl     while (DeclCtx) {
2125a9a4277SAdrian Prantl       if (auto *D = dyn_cast<TagDecl>(DeclCtx))
2135a9a4277SAdrian Prantl         if (!D->isCompleteDefinition())
2145a9a4277SAdrian Prantl           return;
2155a9a4277SAdrian Prantl       DeclCtx = DeclCtx->getParent();
2165a9a4277SAdrian Prantl     }
2175a9a4277SAdrian Prantl 
218cd975018SAdrian Prantl     DebugTypeVisitor DTV(*Builder->getModuleDebugInfo(), *Ctx);
219b3b821f1SAdrian Prantl     DTV.TraverseDecl(D);
2204aa2b3a3SAdrian Prantl     Builder->UpdateCompletedType(D);
2214aa2b3a3SAdrian Prantl   }
2224aa2b3a3SAdrian Prantl 
2234aa2b3a3SAdrian Prantl   void HandleTagDeclRequiredDefinition(const TagDecl *D) override {
2244aa2b3a3SAdrian Prantl     if (Diags.hasErrorOccurred())
2254aa2b3a3SAdrian Prantl       return;
2264aa2b3a3SAdrian Prantl 
2274aa2b3a3SAdrian Prantl     if (const RecordDecl *RD = dyn_cast<RecordDecl>(D))
2288bd4c13fSAdrian Prantl       Builder->getModuleDebugInfo()->completeRequiredType(RD);
2294aa2b3a3SAdrian Prantl   }
2304aa2b3a3SAdrian Prantl 
231c5e3647fSAdrian Prantl   void HandleImplicitImportDecl(ImportDecl *D) override {
232c5e3647fSAdrian Prantl     if (!D->getImportedOwningModule())
233c5e3647fSAdrian Prantl       Builder->getModuleDebugInfo()->EmitImportDecl(*D);
234c5e3647fSAdrian Prantl   }
235c5e3647fSAdrian Prantl 
236bc068586SAdrian Prantl   /// Emit a container holding the serialized AST.
237bc068586SAdrian Prantl   void HandleTranslationUnit(ASTContext &Ctx) override {
238bc068586SAdrian Prantl     assert(M && VMContext && Builder);
239bc068586SAdrian Prantl     // Delete these on function exit.
240bc068586SAdrian Prantl     std::unique_ptr<llvm::LLVMContext> VMContext = std::move(this->VMContext);
241bc068586SAdrian Prantl     std::unique_ptr<llvm::Module> M = std::move(this->M);
242bc068586SAdrian Prantl     std::unique_ptr<CodeGen::CodeGenModule> Builder = std::move(this->Builder);
243bc068586SAdrian Prantl 
244bc068586SAdrian Prantl     if (Diags.hasErrorOccurred())
245bc068586SAdrian Prantl       return;
246bc068586SAdrian Prantl 
247bc068586SAdrian Prantl     M->setTargetTriple(Ctx.getTargetInfo().getTriple().getTriple());
248b214cbc7SJames Y Knight     M->setDataLayout(Ctx.getTargetInfo().getDataLayout());
249c96da8faSAdrian Prantl 
250c96da8faSAdrian Prantl     // PCH files don't have a signature field in the control block,
251c96da8faSAdrian Prantl     // but LLVM detects DWO CUs by looking for a non-zero DWO id.
25260fa2888SDuncan P. N. Exon Smith     // We use the lower 64 bits for debug info.
253*105151caSRaphael Isemann 
25460fa2888SDuncan P. N. Exon Smith     uint64_t Signature =
255*105151caSRaphael Isemann         Buffer->Signature ? Buffer->Signature.truncatedValue() : ~1ULL;
256*105151caSRaphael Isemann 
257c96da8faSAdrian Prantl     Builder->getModuleDebugInfo()->setDwoId(Signature);
258bc068586SAdrian Prantl 
259bc068586SAdrian Prantl     // Finalize the Builder.
260bc068586SAdrian Prantl     if (Builder)
261bc068586SAdrian Prantl       Builder->Release();
262bc068586SAdrian Prantl 
263bc068586SAdrian Prantl     // Ensure the target exists.
264bc068586SAdrian Prantl     std::string Error;
265bc068586SAdrian Prantl     auto Triple = Ctx.getTargetInfo().getTriple();
266bc068586SAdrian Prantl     if (!llvm::TargetRegistry::lookupTarget(Triple.getTriple(), Error))
267bc068586SAdrian Prantl       llvm::report_fatal_error(Error);
268bc068586SAdrian Prantl 
269bc068586SAdrian Prantl     // Emit the serialized Clang AST into its own section.
270bc068586SAdrian Prantl     assert(Buffer->IsComplete && "serialization did not complete");
271bc068586SAdrian Prantl     auto &SerializedAST = Buffer->Data;
272bc068586SAdrian Prantl     auto Size = SerializedAST.size();
273bc068586SAdrian Prantl     auto Int8Ty = llvm::Type::getInt8Ty(*VMContext);
274bc068586SAdrian Prantl     auto *Ty = llvm::ArrayType::get(Int8Ty, Size);
2755a88e1a8SAdrian Prantl     auto *Data = llvm::ConstantDataArray::getString(
2765a88e1a8SAdrian Prantl         *VMContext, StringRef(SerializedAST.data(), Size),
277bc068586SAdrian Prantl         /*AddNull=*/false);
278bc068586SAdrian Prantl     auto *ASTSym = new llvm::GlobalVariable(
279bc068586SAdrian Prantl         *M, Ty, /*constant*/ true, llvm::GlobalVariable::InternalLinkage, Data,
280bc068586SAdrian Prantl         "__clang_ast");
281bc068586SAdrian Prantl     // The on-disk hashtable needs to be aligned.
282c79099e0SGuillaume Chatelet     ASTSym->setAlignment(llvm::Align(8));
283bc068586SAdrian Prantl 
284bc068586SAdrian Prantl     // Mach-O also needs a segment name.
285bc068586SAdrian Prantl     if (Triple.isOSBinFormatMachO())
286bc068586SAdrian Prantl       ASTSym->setSection("__CLANG,__clangast");
287bc068586SAdrian Prantl     // COFF has an eight character length limit.
288bc068586SAdrian Prantl     else if (Triple.isOSBinFormatCOFF())
289bc068586SAdrian Prantl       ASTSym->setSection("clangast");
290bc068586SAdrian Prantl     else
291bc068586SAdrian Prantl       ASTSym->setSection("__clangast");
292bc068586SAdrian Prantl 
2933538b39eSNicola Zaghen     LLVM_DEBUG({
294bc068586SAdrian Prantl       // Print the IR for the PCH container to the debug output.
295bc068586SAdrian Prantl       llvm::SmallString<0> Buffer;
29603f8907fSPeter Collingbourne       clang::EmitBackendOutput(
297888e289eSSaleem Abdulrasool           Diags, HeaderSearchOpts, CodeGenOpts, TargetOpts, LangOpts,
298b214cbc7SJames Y Knight           Ctx.getTargetInfo().getDataLayout(), M.get(),
29903f8907fSPeter Collingbourne           BackendAction::Backend_EmitLL,
3002b3d49b6SJonas Devlieghere           std::make_unique<llvm::raw_svector_ostream>(Buffer));
301bc068586SAdrian Prantl       llvm::dbgs() << Buffer;
302bc068586SAdrian Prantl     });
303bc068586SAdrian Prantl 
304bc068586SAdrian Prantl     // Use the LLVM backend to emit the pch container.
305888e289eSSaleem Abdulrasool     clang::EmitBackendOutput(Diags, HeaderSearchOpts, CodeGenOpts, TargetOpts,
306888e289eSSaleem Abdulrasool                              LangOpts, Ctx.getTargetInfo().getDataLayout(),
307888e289eSSaleem Abdulrasool                              M.get(), BackendAction::Backend_EmitObj,
308888e289eSSaleem Abdulrasool                              std::move(OS));
309bc068586SAdrian Prantl 
310bc068586SAdrian Prantl     // Free the memory for the temporary buffer.
311bc068586SAdrian Prantl     llvm::SmallVector<char, 0> Empty;
312bc068586SAdrian Prantl     SerializedAST = std::move(Empty);
313bc068586SAdrian Prantl   }
314bc068586SAdrian Prantl };
3155a88e1a8SAdrian Prantl 
3167eb5464bSHans Wennborg } // anonymous namespace
317bc068586SAdrian Prantl 
318bc068586SAdrian Prantl std::unique_ptr<ASTConsumer>
319fb2398d0SAdrian Prantl ObjectFilePCHContainerWriter::CreatePCHContainerGenerator(
3201e63b2bdSAdrian Prantl     CompilerInstance &CI, const std::string &MainFileName,
32103f8907fSPeter Collingbourne     const std::string &OutputFileName,
32203f8907fSPeter Collingbourne     std::unique_ptr<llvm::raw_pwrite_stream> OS,
3231e63b2bdSAdrian Prantl     std::shared_ptr<PCHBuffer> Buffer) const {
3242b3d49b6SJonas Devlieghere   return std::make_unique<PCHContainerGenerator>(
32503f8907fSPeter Collingbourne       CI, MainFileName, OutputFileName, std::move(OS), Buffer);
326bc068586SAdrian Prantl }
327bc068586SAdrian Prantl 
32877c89b69SPeter Collingbourne StringRef
32977c89b69SPeter Collingbourne ObjectFilePCHContainerReader::ExtractPCH(llvm::MemoryBufferRef Buffer) const {
33077c89b69SPeter Collingbourne   StringRef PCH;
331576b2dbeSAdrian Prantl   auto OFOrErr = llvm::object::ObjectFile::createObjectFile(Buffer);
332576b2dbeSAdrian Prantl   if (OFOrErr) {
333576b2dbeSAdrian Prantl     auto &OF = OFOrErr.get();
334576b2dbeSAdrian Prantl     bool IsCOFF = isa<llvm::object::COFFObjectFile>(*OF);
335bc068586SAdrian Prantl     // Find the clang AST section in the container.
336576b2dbeSAdrian Prantl     for (auto &Section : OF->sections()) {
337bc068586SAdrian Prantl       StringRef Name;
338a11d302fSGeorge Rimar       if (Expected<StringRef> NameOrErr = Section.getName())
339a11d302fSGeorge Rimar         Name = *NameOrErr;
340a11d302fSGeorge Rimar       else
341a11d302fSGeorge Rimar         consumeError(NameOrErr.takeError());
342a11d302fSGeorge Rimar 
343576b2dbeSAdrian Prantl       if ((!IsCOFF && Name == "__clangast") || (IsCOFF && Name == "clangast")) {
344e183340cSFangrui Song         if (Expected<StringRef> E = Section.getContents())
345e183340cSFangrui Song           return *E;
346e183340cSFangrui Song         else {
347e183340cSFangrui Song           handleAllErrors(E.takeError(), [&](const llvm::ErrorInfoBase &EIB) {
348e183340cSFangrui Song             EIB.log(llvm::errs());
349e183340cSFangrui Song           });
350e183340cSFangrui Song           return "";
351e183340cSFangrui Song         }
352bc068586SAdrian Prantl       }
353bc068586SAdrian Prantl     }
354bc068586SAdrian Prantl   }
355576b2dbeSAdrian Prantl   handleAllErrors(OFOrErr.takeError(), [&](const llvm::ErrorInfoBase &EIB) {
356576b2dbeSAdrian Prantl     if (EIB.convertToErrorCode() ==
357576b2dbeSAdrian Prantl         llvm::object::object_error::invalid_file_type)
358bc068586SAdrian Prantl       // As a fallback, treat the buffer as a raw AST.
35977c89b69SPeter Collingbourne       PCH = Buffer.getBuffer();
360576b2dbeSAdrian Prantl     else
361576b2dbeSAdrian Prantl       EIB.log(llvm::errs());
362576b2dbeSAdrian Prantl   });
36377c89b69SPeter Collingbourne   return PCH;
364bc068586SAdrian Prantl }
365