xref: /src/contrib/llvm-project/clang/lib/CodeGen/ObjectFilePCHContainerOperations.cpp (revision 5f757f3ff9144b609b3c433dfd370cc6bdc191ad) !
151ece4aaSDimitry Andric //===--- ObjectFilePCHContainerOperations.cpp -----------------------------===//
251ece4aaSDimitry Andric //
322989816SDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
422989816SDimitry Andric // See https://llvm.org/LICENSE.txt for license information.
522989816SDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
651ece4aaSDimitry Andric //
751ece4aaSDimitry Andric //===----------------------------------------------------------------------===//
851ece4aaSDimitry Andric 
951ece4aaSDimitry Andric #include "clang/CodeGen/ObjectFilePCHContainerOperations.h"
1051ece4aaSDimitry Andric #include "CGDebugInfo.h"
1151ece4aaSDimitry Andric #include "CodeGenModule.h"
1251ece4aaSDimitry Andric #include "clang/AST/ASTContext.h"
1351ece4aaSDimitry Andric #include "clang/AST/DeclObjC.h"
1451ece4aaSDimitry Andric #include "clang/AST/Expr.h"
1551ece4aaSDimitry Andric #include "clang/AST/RecursiveASTVisitor.h"
16676fbe81SDimitry Andric #include "clang/Basic/CodeGenOptions.h"
1751ece4aaSDimitry Andric #include "clang/Basic/Diagnostic.h"
1851ece4aaSDimitry Andric #include "clang/Basic/TargetInfo.h"
1951ece4aaSDimitry Andric #include "clang/CodeGen/BackendUtil.h"
2045b53394SDimitry Andric #include "clang/Frontend/CompilerInstance.h"
2145b53394SDimitry Andric #include "clang/Lex/HeaderSearch.h"
222b6b257fSDimitry Andric #include "clang/Lex/Preprocessor.h"
2351ece4aaSDimitry Andric #include "llvm/ADT/StringRef.h"
2422989816SDimitry Andric #include "llvm/Bitstream/BitstreamReader.h"
2551ece4aaSDimitry Andric #include "llvm/DebugInfo/DWARF/DWARFContext.h"
2651ece4aaSDimitry Andric #include "llvm/IR/Constants.h"
2751ece4aaSDimitry Andric #include "llvm/IR/DataLayout.h"
2851ece4aaSDimitry Andric #include "llvm/IR/LLVMContext.h"
2951ece4aaSDimitry Andric #include "llvm/IR/Module.h"
30c0981da4SDimitry Andric #include "llvm/MC/TargetRegistry.h"
3151ece4aaSDimitry Andric #include "llvm/Object/COFF.h"
3251ece4aaSDimitry Andric #include "llvm/Object/ObjectFile.h"
332b6b257fSDimitry Andric #include "llvm/Support/Path.h"
3451ece4aaSDimitry Andric #include <memory>
352b6b257fSDimitry Andric #include <utility>
3645b53394SDimitry Andric 
3751ece4aaSDimitry Andric using namespace clang;
3851ece4aaSDimitry Andric 
3951ece4aaSDimitry Andric #define DEBUG_TYPE "pchcontainer"
4051ece4aaSDimitry Andric 
4151ece4aaSDimitry Andric namespace {
4251ece4aaSDimitry Andric class PCHContainerGenerator : public ASTConsumer {
4351ece4aaSDimitry Andric   DiagnosticsEngine &Diags;
4451ece4aaSDimitry Andric   const std::string MainFileName;
452b6b257fSDimitry Andric   const std::string OutputFileName;
4651ece4aaSDimitry Andric   ASTContext *Ctx;
4745b53394SDimitry Andric   ModuleMap &MMap;
4808e8dd7bSDimitry Andric   IntrusiveRefCntPtr<llvm::vfs::FileSystem> FS;
4951ece4aaSDimitry Andric   const HeaderSearchOptions &HeaderSearchOpts;
5051ece4aaSDimitry Andric   const PreprocessorOptions &PreprocessorOpts;
5151ece4aaSDimitry Andric   CodeGenOptions CodeGenOpts;
5251ece4aaSDimitry Andric   const TargetOptions TargetOpts;
53b60736ecSDimitry Andric   LangOptions LangOpts;
5451ece4aaSDimitry Andric   std::unique_ptr<llvm::LLVMContext> VMContext;
5551ece4aaSDimitry Andric   std::unique_ptr<llvm::Module> M;
5651ece4aaSDimitry Andric   std::unique_ptr<CodeGen::CodeGenModule> Builder;
572b6b257fSDimitry Andric   std::unique_ptr<raw_pwrite_stream> OS;
5851ece4aaSDimitry Andric   std::shared_ptr<PCHBuffer> Buffer;
5951ece4aaSDimitry Andric 
6045b53394SDimitry Andric   /// Visit every type and emit debug info for it.
6145b53394SDimitry Andric   struct DebugTypeVisitor : public RecursiveASTVisitor<DebugTypeVisitor> {
6245b53394SDimitry Andric     clang::CodeGen::CGDebugInfo &DI;
6345b53394SDimitry Andric     ASTContext &Ctx;
DebugTypeVisitor__anon0f3c64ac0111::PCHContainerGenerator::DebugTypeVisitor642b6b257fSDimitry Andric     DebugTypeVisitor(clang::CodeGen::CGDebugInfo &DI, ASTContext &Ctx)
652b6b257fSDimitry Andric         : DI(DI), Ctx(Ctx) {}
6645b53394SDimitry Andric 
6745b53394SDimitry Andric     /// Determine whether this type can be represented in DWARF.
CanRepresent__anon0f3c64ac0111::PCHContainerGenerator::DebugTypeVisitor6845b53394SDimitry Andric     static bool CanRepresent(const Type *Ty) {
6945b53394SDimitry Andric       return !Ty->isDependentType() && !Ty->isUndeducedType();
7045b53394SDimitry Andric     }
7145b53394SDimitry Andric 
VisitImportDecl__anon0f3c64ac0111::PCHContainerGenerator::DebugTypeVisitor7245b53394SDimitry Andric     bool VisitImportDecl(ImportDecl *D) {
7348675466SDimitry Andric       if (!D->getImportedOwningModule())
7448675466SDimitry Andric         DI.EmitImportDecl(*D);
7545b53394SDimitry Andric       return true;
7645b53394SDimitry Andric     }
7745b53394SDimitry Andric 
VisitTypeDecl__anon0f3c64ac0111::PCHContainerGenerator::DebugTypeVisitor7845b53394SDimitry Andric     bool VisitTypeDecl(TypeDecl *D) {
790414e226SDimitry Andric       // TagDecls may be deferred until after all decls have been merged and we
800414e226SDimitry Andric       // know the complete type. Pure forward declarations will be skipped, but
810414e226SDimitry Andric       // they don't need to be emitted into the module anyway.
822b6b257fSDimitry Andric       if (auto *TD = dyn_cast<TagDecl>(D))
832b6b257fSDimitry Andric         if (!TD->isCompleteDefinition())
840414e226SDimitry Andric           return true;
850414e226SDimitry Andric 
8645b53394SDimitry Andric       QualType QualTy = Ctx.getTypeDeclType(D);
8745b53394SDimitry Andric       if (!QualTy.isNull() && CanRepresent(QualTy.getTypePtr()))
8845b53394SDimitry Andric         DI.getOrCreateStandaloneType(QualTy, D->getLocation());
8945b53394SDimitry Andric       return true;
9045b53394SDimitry Andric     }
9145b53394SDimitry Andric 
VisitObjCInterfaceDecl__anon0f3c64ac0111::PCHContainerGenerator::DebugTypeVisitor9245b53394SDimitry Andric     bool VisitObjCInterfaceDecl(ObjCInterfaceDecl *D) {
9345b53394SDimitry Andric       QualType QualTy(D->getTypeForDecl(), 0);
9445b53394SDimitry Andric       if (!QualTy.isNull() && CanRepresent(QualTy.getTypePtr()))
9545b53394SDimitry Andric         DI.getOrCreateStandaloneType(QualTy, D->getLocation());
9645b53394SDimitry Andric       return true;
9745b53394SDimitry Andric     }
9845b53394SDimitry Andric 
VisitFunctionDecl__anon0f3c64ac0111::PCHContainerGenerator::DebugTypeVisitor9945b53394SDimitry Andric     bool VisitFunctionDecl(FunctionDecl *D) {
100145449b1SDimitry Andric       // Skip deduction guides.
101145449b1SDimitry Andric       if (isa<CXXDeductionGuideDecl>(D))
102145449b1SDimitry Andric         return true;
103145449b1SDimitry Andric 
10445b53394SDimitry Andric       if (isa<CXXMethodDecl>(D))
10545b53394SDimitry Andric         // This is not yet supported. Constructing the `this' argument
10645b53394SDimitry Andric         // mandates a CodeGenFunction.
10745b53394SDimitry Andric         return true;
10845b53394SDimitry Andric 
10945b53394SDimitry Andric       SmallVector<QualType, 16> ArgTypes;
110e3b55780SDimitry Andric       for (auto *i : D->parameters())
11145b53394SDimitry Andric         ArgTypes.push_back(i->getType());
11245b53394SDimitry Andric       QualType RetTy = D->getReturnType();
11345b53394SDimitry Andric       QualType FnTy = Ctx.getFunctionType(RetTy, ArgTypes,
11445b53394SDimitry Andric                                           FunctionProtoType::ExtProtoInfo());
11545b53394SDimitry Andric       if (CanRepresent(FnTy.getTypePtr()))
11645b53394SDimitry Andric         DI.EmitFunctionDecl(D, D->getLocation(), FnTy);
11745b53394SDimitry Andric       return true;
11845b53394SDimitry Andric     }
11945b53394SDimitry Andric 
VisitObjCMethodDecl__anon0f3c64ac0111::PCHContainerGenerator::DebugTypeVisitor12045b53394SDimitry Andric     bool VisitObjCMethodDecl(ObjCMethodDecl *D) {
12145b53394SDimitry Andric       if (!D->getClassInterface())
12245b53394SDimitry Andric         return true;
12345b53394SDimitry Andric 
12445b53394SDimitry Andric       bool selfIsPseudoStrong, selfIsConsumed;
12545b53394SDimitry Andric       SmallVector<QualType, 16> ArgTypes;
12645b53394SDimitry Andric       ArgTypes.push_back(D->getSelfType(Ctx, D->getClassInterface(),
12745b53394SDimitry Andric                                         selfIsPseudoStrong, selfIsConsumed));
12845b53394SDimitry Andric       ArgTypes.push_back(Ctx.getObjCSelType());
129e3b55780SDimitry Andric       for (auto *i : D->parameters())
13045b53394SDimitry Andric         ArgTypes.push_back(i->getType());
13145b53394SDimitry Andric       QualType RetTy = D->getReturnType();
13245b53394SDimitry Andric       QualType FnTy = Ctx.getFunctionType(RetTy, ArgTypes,
13345b53394SDimitry Andric                                           FunctionProtoType::ExtProtoInfo());
13445b53394SDimitry Andric       if (CanRepresent(FnTy.getTypePtr()))
13545b53394SDimitry Andric         DI.EmitFunctionDecl(D, D->getLocation(), FnTy);
13645b53394SDimitry Andric       return true;
13745b53394SDimitry Andric     }
13845b53394SDimitry Andric   };
13945b53394SDimitry Andric 
14051ece4aaSDimitry Andric public:
PCHContainerGenerator(CompilerInstance & CI,const std::string & MainFileName,const std::string & OutputFileName,std::unique_ptr<raw_pwrite_stream> OS,std::shared_ptr<PCHBuffer> Buffer)14145b53394SDimitry Andric   PCHContainerGenerator(CompilerInstance &CI, const std::string &MainFileName,
14251ece4aaSDimitry Andric                         const std::string &OutputFileName,
1432b6b257fSDimitry Andric                         std::unique_ptr<raw_pwrite_stream> OS,
14451ece4aaSDimitry Andric                         std::shared_ptr<PCHBuffer> Buffer)
1452b6b257fSDimitry Andric       : Diags(CI.getDiagnostics()), MainFileName(MainFileName),
1462b6b257fSDimitry Andric         OutputFileName(OutputFileName), Ctx(nullptr),
14745b53394SDimitry Andric         MMap(CI.getPreprocessor().getHeaderSearchInfo().getModuleMap()),
14808e8dd7bSDimitry Andric         FS(&CI.getVirtualFileSystem()),
14945b53394SDimitry Andric         HeaderSearchOpts(CI.getHeaderSearchOpts()),
15045b53394SDimitry Andric         PreprocessorOpts(CI.getPreprocessorOpts()),
1512b6b257fSDimitry Andric         TargetOpts(CI.getTargetOpts()), LangOpts(CI.getLangOpts()),
1522b6b257fSDimitry Andric         OS(std::move(OS)), Buffer(std::move(Buffer)) {
15351ece4aaSDimitry Andric     // The debug info output isn't affected by CodeModel and
15451ece4aaSDimitry Andric     // ThreadModel, but the backend expects them to be nonempty.
15551ece4aaSDimitry Andric     CodeGenOpts.CodeModel = "default";
156b60736ecSDimitry Andric     LangOpts.setThreadModel(LangOptions::ThreadModelKind::Single);
15745b53394SDimitry Andric     CodeGenOpts.DebugTypeExtRefs = true;
158de51d671SDimitry Andric     // When building a module MainFileName is the name of the modulemap file.
159de51d671SDimitry Andric     CodeGenOpts.MainFileName =
160de51d671SDimitry Andric         LangOpts.CurrentModule.empty() ? MainFileName : LangOpts.CurrentModule;
1617fa27ce4SDimitry Andric     CodeGenOpts.setDebugInfo(llvm::codegenoptions::FullDebugInfo);
1622b6b257fSDimitry Andric     CodeGenOpts.setDebuggerTuning(CI.getCodeGenOpts().getDebuggerTuning());
163b1c73532SDimitry Andric     CodeGenOpts.DwarfVersion = CI.getCodeGenOpts().DwarfVersion;
164b1c73532SDimitry Andric     CodeGenOpts.DebugCompilationDir =
165b1c73532SDimitry Andric         CI.getInvocation().getCodeGenOpts().DebugCompilationDir;
166676fbe81SDimitry Andric     CodeGenOpts.DebugPrefixMap =
167676fbe81SDimitry Andric         CI.getInvocation().getCodeGenOpts().DebugPrefixMap;
1686f8fc217SDimitry Andric     CodeGenOpts.DebugStrictDwarf = CI.getCodeGenOpts().DebugStrictDwarf;
16951ece4aaSDimitry Andric   }
17051ece4aaSDimitry Andric 
17145b53394SDimitry Andric   ~PCHContainerGenerator() override = default;
17251ece4aaSDimitry Andric 
Initialize(ASTContext & Context)17351ece4aaSDimitry Andric   void Initialize(ASTContext &Context) override {
17445b53394SDimitry Andric     assert(!Ctx && "initialized multiple times");
17545b53394SDimitry Andric 
17651ece4aaSDimitry Andric     Ctx = &Context;
17751ece4aaSDimitry Andric     VMContext.reset(new llvm::LLVMContext());
17851ece4aaSDimitry Andric     M.reset(new llvm::Module(MainFileName, *VMContext));
179344a3780SDimitry Andric     M->setDataLayout(Ctx->getTargetInfo().getDataLayoutString());
18045b53394SDimitry Andric     Builder.reset(new CodeGen::CodeGenModule(
18108e8dd7bSDimitry Andric         *Ctx, FS, HeaderSearchOpts, PreprocessorOpts, CodeGenOpts, *M, Diags));
1822b6b257fSDimitry Andric 
1832b6b257fSDimitry Andric     // Prepare CGDebugInfo to emit debug info for a clang module.
1842b6b257fSDimitry Andric     auto *DI = Builder->getModuleDebugInfo();
1852b6b257fSDimitry Andric     StringRef ModuleName = llvm::sys::path::filename(MainFileName);
186cfca06d7SDimitry Andric     DI->setPCHDescriptor(
187cfca06d7SDimitry Andric         {ModuleName, "", OutputFileName, ASTFileSignature::createDISentinel()});
1882b6b257fSDimitry Andric     DI->setModuleMap(MMap);
18945b53394SDimitry Andric   }
19045b53394SDimitry Andric 
HandleTopLevelDecl(DeclGroupRef D)19145b53394SDimitry Andric   bool HandleTopLevelDecl(DeclGroupRef D) override {
19245b53394SDimitry Andric     if (Diags.hasErrorOccurred())
19345b53394SDimitry Andric       return true;
19445b53394SDimitry Andric 
19545b53394SDimitry Andric     // Collect debug info for all decls in this group.
19645b53394SDimitry Andric     for (auto *I : D)
19745b53394SDimitry Andric       if (!I->isFromASTFile()) {
1982b6b257fSDimitry Andric         DebugTypeVisitor DTV(*Builder->getModuleDebugInfo(), *Ctx);
19945b53394SDimitry Andric         DTV.TraverseDecl(I);
20045b53394SDimitry Andric       }
20145b53394SDimitry Andric     return true;
20245b53394SDimitry Andric   }
20345b53394SDimitry Andric 
HandleTopLevelDeclInObjCContainer(DeclGroupRef D)20445b53394SDimitry Andric   void HandleTopLevelDeclInObjCContainer(DeclGroupRef D) override {
20545b53394SDimitry Andric     HandleTopLevelDecl(D);
20645b53394SDimitry Andric   }
20745b53394SDimitry Andric 
HandleTagDeclDefinition(TagDecl * D)20845b53394SDimitry Andric   void HandleTagDeclDefinition(TagDecl *D) override {
20945b53394SDimitry Andric     if (Diags.hasErrorOccurred())
21045b53394SDimitry Andric       return;
21145b53394SDimitry Andric 
2120414e226SDimitry Andric     if (D->isFromASTFile())
2130414e226SDimitry Andric       return;
2140414e226SDimitry Andric 
2152b6b257fSDimitry Andric     // Anonymous tag decls are deferred until we are building their declcontext.
2162b6b257fSDimitry Andric     if (D->getName().empty())
2172b6b257fSDimitry Andric       return;
2182b6b257fSDimitry Andric 
2192b6b257fSDimitry Andric     // Defer tag decls until their declcontext is complete.
2202b6b257fSDimitry Andric     auto *DeclCtx = D->getDeclContext();
2212b6b257fSDimitry Andric     while (DeclCtx) {
2222b6b257fSDimitry Andric       if (auto *D = dyn_cast<TagDecl>(DeclCtx))
2232b6b257fSDimitry Andric         if (!D->isCompleteDefinition())
2242b6b257fSDimitry Andric           return;
2252b6b257fSDimitry Andric       DeclCtx = DeclCtx->getParent();
2262b6b257fSDimitry Andric     }
2272b6b257fSDimitry Andric 
2282b6b257fSDimitry Andric     DebugTypeVisitor DTV(*Builder->getModuleDebugInfo(), *Ctx);
2290414e226SDimitry Andric     DTV.TraverseDecl(D);
23045b53394SDimitry Andric     Builder->UpdateCompletedType(D);
23145b53394SDimitry Andric   }
23245b53394SDimitry Andric 
HandleTagDeclRequiredDefinition(const TagDecl * D)23345b53394SDimitry Andric   void HandleTagDeclRequiredDefinition(const TagDecl *D) override {
23445b53394SDimitry Andric     if (Diags.hasErrorOccurred())
23545b53394SDimitry Andric       return;
23645b53394SDimitry Andric 
23745b53394SDimitry Andric     if (const RecordDecl *RD = dyn_cast<RecordDecl>(D))
23845b53394SDimitry Andric       Builder->getModuleDebugInfo()->completeRequiredType(RD);
23951ece4aaSDimitry Andric   }
24051ece4aaSDimitry Andric 
HandleImplicitImportDecl(ImportDecl * D)24148675466SDimitry Andric   void HandleImplicitImportDecl(ImportDecl *D) override {
24248675466SDimitry Andric     if (!D->getImportedOwningModule())
24348675466SDimitry Andric       Builder->getModuleDebugInfo()->EmitImportDecl(*D);
24448675466SDimitry Andric   }
24548675466SDimitry Andric 
24651ece4aaSDimitry Andric   /// Emit a container holding the serialized AST.
HandleTranslationUnit(ASTContext & Ctx)24751ece4aaSDimitry Andric   void HandleTranslationUnit(ASTContext &Ctx) override {
24851ece4aaSDimitry Andric     assert(M && VMContext && Builder);
24951ece4aaSDimitry Andric     // Delete these on function exit.
25051ece4aaSDimitry Andric     std::unique_ptr<llvm::LLVMContext> VMContext = std::move(this->VMContext);
25151ece4aaSDimitry Andric     std::unique_ptr<llvm::Module> M = std::move(this->M);
25251ece4aaSDimitry Andric     std::unique_ptr<CodeGen::CodeGenModule> Builder = std::move(this->Builder);
25351ece4aaSDimitry Andric 
25451ece4aaSDimitry Andric     if (Diags.hasErrorOccurred())
25551ece4aaSDimitry Andric       return;
25651ece4aaSDimitry Andric 
25751ece4aaSDimitry Andric     M->setTargetTriple(Ctx.getTargetInfo().getTriple().getTriple());
258344a3780SDimitry Andric     M->setDataLayout(Ctx.getTargetInfo().getDataLayoutString());
2592b6b257fSDimitry Andric 
2602b6b257fSDimitry Andric     // PCH files don't have a signature field in the control block,
2612b6b257fSDimitry Andric     // but LLVM detects DWO CUs by looking for a non-zero DWO id.
2627442d6faSDimitry Andric     // We use the lower 64 bits for debug info.
263b60736ecSDimitry Andric 
2647442d6faSDimitry Andric     uint64_t Signature =
265b60736ecSDimitry Andric         Buffer->Signature ? Buffer->Signature.truncatedValue() : ~1ULL;
266b60736ecSDimitry Andric 
2672b6b257fSDimitry Andric     Builder->getModuleDebugInfo()->setDwoId(Signature);
26851ece4aaSDimitry Andric 
26951ece4aaSDimitry Andric     // Finalize the Builder.
27051ece4aaSDimitry Andric     if (Builder)
27151ece4aaSDimitry Andric       Builder->Release();
27251ece4aaSDimitry Andric 
27351ece4aaSDimitry Andric     // Ensure the target exists.
27451ece4aaSDimitry Andric     std::string Error;
27551ece4aaSDimitry Andric     auto Triple = Ctx.getTargetInfo().getTriple();
27651ece4aaSDimitry Andric     if (!llvm::TargetRegistry::lookupTarget(Triple.getTriple(), Error))
277c0981da4SDimitry Andric       llvm::report_fatal_error(llvm::Twine(Error));
27851ece4aaSDimitry Andric 
27951ece4aaSDimitry Andric     // Emit the serialized Clang AST into its own section.
28051ece4aaSDimitry Andric     assert(Buffer->IsComplete && "serialization did not complete");
28151ece4aaSDimitry Andric     auto &SerializedAST = Buffer->Data;
28251ece4aaSDimitry Andric     auto Size = SerializedAST.size();
283c0981da4SDimitry Andric 
284c0981da4SDimitry Andric     if (Triple.isOSBinFormatWasm()) {
285c0981da4SDimitry Andric       // Emit __clangast in custom section instead of named data segment
286c0981da4SDimitry Andric       // to find it while iterating sections.
287c0981da4SDimitry Andric       // This could be avoided if all data segements (the wasm sense) were
288c0981da4SDimitry Andric       // represented as their own sections (in the llvm sense).
289c0981da4SDimitry Andric       // TODO: https://github.com/WebAssembly/tool-conventions/issues/138
290c0981da4SDimitry Andric       llvm::NamedMDNode *MD =
291c0981da4SDimitry Andric           M->getOrInsertNamedMetadata("wasm.custom_sections");
292c0981da4SDimitry Andric       llvm::Metadata *Ops[2] = {
293c0981da4SDimitry Andric           llvm::MDString::get(*VMContext, "__clangast"),
294c0981da4SDimitry Andric           llvm::MDString::get(*VMContext,
295c0981da4SDimitry Andric                               StringRef(SerializedAST.data(), Size))};
296c0981da4SDimitry Andric       auto *NameAndContent = llvm::MDTuple::get(*VMContext, Ops);
297c0981da4SDimitry Andric       MD->addOperand(NameAndContent);
298c0981da4SDimitry Andric     } else {
29951ece4aaSDimitry Andric       auto Int8Ty = llvm::Type::getInt8Ty(*VMContext);
30051ece4aaSDimitry Andric       auto *Ty = llvm::ArrayType::get(Int8Ty, Size);
30151ece4aaSDimitry Andric       auto *Data = llvm::ConstantDataArray::getString(
30251ece4aaSDimitry Andric           *VMContext, StringRef(SerializedAST.data(), Size),
30351ece4aaSDimitry Andric           /*AddNull=*/false);
30451ece4aaSDimitry Andric       auto *ASTSym = new llvm::GlobalVariable(
305c0981da4SDimitry Andric           *M, Ty, /*constant*/ true, llvm::GlobalVariable::InternalLinkage,
306c0981da4SDimitry Andric           Data, "__clang_ast");
30751ece4aaSDimitry Andric       // The on-disk hashtable needs to be aligned.
308519fc96cSDimitry Andric       ASTSym->setAlignment(llvm::Align(8));
30951ece4aaSDimitry Andric 
31051ece4aaSDimitry Andric       // Mach-O also needs a segment name.
31151ece4aaSDimitry Andric       if (Triple.isOSBinFormatMachO())
31251ece4aaSDimitry Andric         ASTSym->setSection("__CLANG,__clangast");
31351ece4aaSDimitry Andric       // COFF has an eight character length limit.
31451ece4aaSDimitry Andric       else if (Triple.isOSBinFormatCOFF())
31551ece4aaSDimitry Andric         ASTSym->setSection("clangast");
31651ece4aaSDimitry Andric       else
31751ece4aaSDimitry Andric         ASTSym->setSection("__clangast");
318c0981da4SDimitry Andric     }
31951ece4aaSDimitry Andric 
32048675466SDimitry Andric     LLVM_DEBUG({
32151ece4aaSDimitry Andric       // Print the IR for the PCH container to the debug output.
32251ece4aaSDimitry Andric       llvm::SmallString<0> Buffer;
3232b6b257fSDimitry Andric       clang::EmitBackendOutput(
3246694ed09SDimitry Andric           Diags, HeaderSearchOpts, CodeGenOpts, TargetOpts, LangOpts,
325344a3780SDimitry Andric           Ctx.getTargetInfo().getDataLayoutString(), M.get(),
3267fa27ce4SDimitry Andric           BackendAction::Backend_EmitLL, FS,
327519fc96cSDimitry Andric           std::make_unique<llvm::raw_svector_ostream>(Buffer));
32851ece4aaSDimitry Andric       llvm::dbgs() << Buffer;
32951ece4aaSDimitry Andric     });
33051ece4aaSDimitry Andric 
33151ece4aaSDimitry Andric     // Use the LLVM backend to emit the pch container.
3326694ed09SDimitry Andric     clang::EmitBackendOutput(Diags, HeaderSearchOpts, CodeGenOpts, TargetOpts,
333344a3780SDimitry Andric                              LangOpts,
334344a3780SDimitry Andric                              Ctx.getTargetInfo().getDataLayoutString(), M.get(),
3357fa27ce4SDimitry Andric                              BackendAction::Backend_EmitObj, FS, std::move(OS));
33651ece4aaSDimitry Andric 
33751ece4aaSDimitry Andric     // Free the memory for the temporary buffer.
33851ece4aaSDimitry Andric     llvm::SmallVector<char, 0> Empty;
33951ece4aaSDimitry Andric     SerializedAST = std::move(Empty);
34051ece4aaSDimitry Andric   }
34151ece4aaSDimitry Andric };
34251ece4aaSDimitry Andric 
34345b53394SDimitry Andric } // anonymous namespace
34451ece4aaSDimitry Andric 
34551ece4aaSDimitry Andric std::unique_ptr<ASTConsumer>
CreatePCHContainerGenerator(CompilerInstance & CI,const std::string & MainFileName,const std::string & OutputFileName,std::unique_ptr<llvm::raw_pwrite_stream> OS,std::shared_ptr<PCHBuffer> Buffer) const34636c5ade2SDimitry Andric ObjectFilePCHContainerWriter::CreatePCHContainerGenerator(
34745b53394SDimitry Andric     CompilerInstance &CI, const std::string &MainFileName,
3482b6b257fSDimitry Andric     const std::string &OutputFileName,
3492b6b257fSDimitry Andric     std::unique_ptr<llvm::raw_pwrite_stream> OS,
35051ece4aaSDimitry Andric     std::shared_ptr<PCHBuffer> Buffer) const {
351519fc96cSDimitry Andric   return std::make_unique<PCHContainerGenerator>(
3522b6b257fSDimitry Andric       CI, MainFileName, OutputFileName, std::move(OS), Buffer);
35351ece4aaSDimitry Andric }
35451ece4aaSDimitry Andric 
getFormats() const3557fa27ce4SDimitry Andric ArrayRef<StringRef> ObjectFilePCHContainerReader::getFormats() const {
3567fa27ce4SDimitry Andric   static StringRef Formats[] = {"obj", "raw"};
3577fa27ce4SDimitry Andric   return Formats;
3587fa27ce4SDimitry Andric }
3597fa27ce4SDimitry Andric 
360bab175ecSDimitry Andric StringRef
ExtractPCH(llvm::MemoryBufferRef Buffer) const361bab175ecSDimitry Andric ObjectFilePCHContainerReader::ExtractPCH(llvm::MemoryBufferRef Buffer) const {
362bab175ecSDimitry Andric   StringRef PCH;
363bab175ecSDimitry Andric   auto OFOrErr = llvm::object::ObjectFile::createObjectFile(Buffer);
364bab175ecSDimitry Andric   if (OFOrErr) {
365bab175ecSDimitry Andric     auto &OF = OFOrErr.get();
366bab175ecSDimitry Andric     bool IsCOFF = isa<llvm::object::COFFObjectFile>(*OF);
36751ece4aaSDimitry Andric     // Find the clang AST section in the container.
368bab175ecSDimitry Andric     for (auto &Section : OF->sections()) {
36951ece4aaSDimitry Andric       StringRef Name;
370519fc96cSDimitry Andric       if (Expected<StringRef> NameOrErr = Section.getName())
371519fc96cSDimitry Andric         Name = *NameOrErr;
372519fc96cSDimitry Andric       else
373519fc96cSDimitry Andric         consumeError(NameOrErr.takeError());
374519fc96cSDimitry Andric 
375bab175ecSDimitry Andric       if ((!IsCOFF && Name == "__clangast") || (IsCOFF && Name == "clangast")) {
37622989816SDimitry Andric         if (Expected<StringRef> E = Section.getContents())
37722989816SDimitry Andric           return *E;
37822989816SDimitry Andric         else {
37922989816SDimitry Andric           handleAllErrors(E.takeError(), [&](const llvm::ErrorInfoBase &EIB) {
38022989816SDimitry Andric             EIB.log(llvm::errs());
38122989816SDimitry Andric           });
38222989816SDimitry Andric           return "";
38322989816SDimitry Andric         }
38451ece4aaSDimitry Andric       }
38551ece4aaSDimitry Andric     }
38651ece4aaSDimitry Andric   }
387bab175ecSDimitry Andric   handleAllErrors(OFOrErr.takeError(), [&](const llvm::ErrorInfoBase &EIB) {
388bab175ecSDimitry Andric     if (EIB.convertToErrorCode() ==
389bab175ecSDimitry Andric         llvm::object::object_error::invalid_file_type)
39051ece4aaSDimitry Andric       // As a fallback, treat the buffer as a raw AST.
391bab175ecSDimitry Andric       PCH = Buffer.getBuffer();
392bab175ecSDimitry Andric     else
393bab175ecSDimitry Andric       EIB.log(llvm::errs());
394bab175ecSDimitry Andric   });
395bab175ecSDimitry Andric   return PCH;
39651ece4aaSDimitry Andric }
397