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"
3089b57061SReid Kleckner #include "llvm/MC/TargetRegistry.h"
31bc068586SAdrian Prantl #include "llvm/Object/COFF.h"
32bc068586SAdrian Prantl #include "llvm/Object/ObjectFile.h"
333a2d4947SAdrian Prantl #include "llvm/Support/Path.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;
48*8dfaecc4SArgyrios Kyrtzidis   IntrusiveRefCntPtr<llvm::vfs::FileSystem> FS;
49bc068586SAdrian Prantl   const HeaderSearchOptions &HeaderSearchOpts;
50bc068586SAdrian Prantl   const PreprocessorOptions &PreprocessorOpts;
51bc068586SAdrian Prantl   CodeGenOptions CodeGenOpts;
52bc068586SAdrian Prantl   const TargetOptions TargetOpts;
5315a3ae1aSZequan Wu   LangOptions LangOpts;
54bc068586SAdrian Prantl   std::unique_ptr<llvm::LLVMContext> VMContext;
55bc068586SAdrian Prantl   std::unique_ptr<llvm::Module> M;
56bc068586SAdrian Prantl   std::unique_ptr<CodeGen::CodeGenModule> Builder;
5703f8907fSPeter Collingbourne   std::unique_ptr<raw_pwrite_stream> OS;
58bc068586SAdrian Prantl   std::shared_ptr<PCHBuffer> Buffer;
59bc068586SAdrian Prantl 
604aa2b3a3SAdrian Prantl   /// Visit every type and emit debug info for it.
614aa2b3a3SAdrian Prantl   struct DebugTypeVisitor : public RecursiveASTVisitor<DebugTypeVisitor> {
624aa2b3a3SAdrian Prantl     clang::CodeGen::CGDebugInfo &DI;
634aa2b3a3SAdrian Prantl     ASTContext &Ctx;
DebugTypeVisitor__anon8fee51a70111::PCHContainerGenerator::DebugTypeVisitor64cd975018SAdrian Prantl     DebugTypeVisitor(clang::CodeGen::CGDebugInfo &DI, ASTContext &Ctx)
65cd975018SAdrian Prantl         : DI(DI), Ctx(Ctx) {}
664aa2b3a3SAdrian Prantl 
674aa2b3a3SAdrian Prantl     /// Determine whether this type can be represented in DWARF.
CanRepresent__anon8fee51a70111::PCHContainerGenerator::DebugTypeVisitor684aa2b3a3SAdrian Prantl     static bool CanRepresent(const Type *Ty) {
694aa2b3a3SAdrian Prantl       return !Ty->isDependentType() && !Ty->isUndeducedType();
704aa2b3a3SAdrian Prantl     }
714aa2b3a3SAdrian Prantl 
VisitImportDecl__anon8fee51a70111::PCHContainerGenerator::DebugTypeVisitor7285d938aaSAdrian Prantl     bool VisitImportDecl(ImportDecl *D) {
731b88acedSAdrian Prantl       if (!D->getImportedOwningModule())
741b88acedSAdrian Prantl         DI.EmitImportDecl(*D);
7585d938aaSAdrian Prantl       return true;
7685d938aaSAdrian Prantl     }
7785d938aaSAdrian Prantl 
VisitTypeDecl__anon8fee51a70111::PCHContainerGenerator::DebugTypeVisitor784aa2b3a3SAdrian Prantl     bool VisitTypeDecl(TypeDecl *D) {
79b3b821f1SAdrian Prantl       // TagDecls may be deferred until after all decls have been merged and we
80b3b821f1SAdrian Prantl       // know the complete type. Pure forward declarations will be skipped, but
81b3b821f1SAdrian Prantl       // they don't need to be emitted into the module anyway.
82cd975018SAdrian Prantl       if (auto *TD = dyn_cast<TagDecl>(D))
83cd975018SAdrian Prantl         if (!TD->isCompleteDefinition())
84b3b821f1SAdrian Prantl           return true;
85b3b821f1SAdrian Prantl 
864aa2b3a3SAdrian Prantl       QualType QualTy = Ctx.getTypeDeclType(D);
874aa2b3a3SAdrian Prantl       if (!QualTy.isNull() && CanRepresent(QualTy.getTypePtr()))
884aa2b3a3SAdrian Prantl         DI.getOrCreateStandaloneType(QualTy, D->getLocation());
894aa2b3a3SAdrian Prantl       return true;
904aa2b3a3SAdrian Prantl     }
914aa2b3a3SAdrian Prantl 
VisitObjCInterfaceDecl__anon8fee51a70111::PCHContainerGenerator::DebugTypeVisitor92748a6cd1SAdrian Prantl     bool VisitObjCInterfaceDecl(ObjCInterfaceDecl *D) {
93748a6cd1SAdrian Prantl       QualType QualTy(D->getTypeForDecl(), 0);
94748a6cd1SAdrian Prantl       if (!QualTy.isNull() && CanRepresent(QualTy.getTypePtr()))
95748a6cd1SAdrian Prantl         DI.getOrCreateStandaloneType(QualTy, D->getLocation());
96748a6cd1SAdrian Prantl       return true;
97748a6cd1SAdrian Prantl     }
98748a6cd1SAdrian Prantl 
VisitFunctionDecl__anon8fee51a70111::PCHContainerGenerator::DebugTypeVisitor99748a6cd1SAdrian Prantl     bool VisitFunctionDecl(FunctionDecl *D) {
1003ba6ace3SAkira Hatanaka       // Skip deduction guides.
1013ba6ace3SAkira Hatanaka       if (isa<CXXDeductionGuideDecl>(D))
1023ba6ace3SAkira Hatanaka         return true;
1033ba6ace3SAkira Hatanaka 
104748a6cd1SAdrian Prantl       if (isa<CXXMethodDecl>(D))
105748a6cd1SAdrian Prantl         // This is not yet supported. Constructing the `this' argument
106748a6cd1SAdrian Prantl         // mandates a CodeGenFunction.
107748a6cd1SAdrian Prantl         return true;
108748a6cd1SAdrian Prantl 
109748a6cd1SAdrian Prantl       SmallVector<QualType, 16> ArgTypes;
11059f77921SDavid Majnemer       for (auto i : D->parameters())
111748a6cd1SAdrian Prantl         ArgTypes.push_back(i->getType());
112748a6cd1SAdrian Prantl       QualType RetTy = D->getReturnType();
113748a6cd1SAdrian Prantl       QualType FnTy = Ctx.getFunctionType(RetTy, ArgTypes,
114748a6cd1SAdrian Prantl                                           FunctionProtoType::ExtProtoInfo());
115748a6cd1SAdrian Prantl       if (CanRepresent(FnTy.getTypePtr()))
116748a6cd1SAdrian Prantl         DI.EmitFunctionDecl(D, D->getLocation(), FnTy);
117748a6cd1SAdrian Prantl       return true;
118748a6cd1SAdrian Prantl     }
119748a6cd1SAdrian Prantl 
VisitObjCMethodDecl__anon8fee51a70111::PCHContainerGenerator::DebugTypeVisitor120748a6cd1SAdrian Prantl     bool VisitObjCMethodDecl(ObjCMethodDecl *D) {
121748a6cd1SAdrian Prantl       if (!D->getClassInterface())
122748a6cd1SAdrian Prantl         return true;
123748a6cd1SAdrian Prantl 
124748a6cd1SAdrian Prantl       bool selfIsPseudoStrong, selfIsConsumed;
125748a6cd1SAdrian Prantl       SmallVector<QualType, 16> ArgTypes;
126748a6cd1SAdrian Prantl       ArgTypes.push_back(D->getSelfType(Ctx, D->getClassInterface(),
127748a6cd1SAdrian Prantl                                         selfIsPseudoStrong, selfIsConsumed));
128748a6cd1SAdrian Prantl       ArgTypes.push_back(Ctx.getObjCSelType());
12959f77921SDavid Majnemer       for (auto i : D->parameters())
130748a6cd1SAdrian Prantl         ArgTypes.push_back(i->getType());
131748a6cd1SAdrian Prantl       QualType RetTy = D->getReturnType();
132748a6cd1SAdrian Prantl       QualType FnTy = Ctx.getFunctionType(RetTy, ArgTypes,
133748a6cd1SAdrian Prantl                                           FunctionProtoType::ExtProtoInfo());
134748a6cd1SAdrian Prantl       if (CanRepresent(FnTy.getTypePtr()))
135748a6cd1SAdrian Prantl         DI.EmitFunctionDecl(D, D->getLocation(), FnTy);
136748a6cd1SAdrian Prantl       return true;
137748a6cd1SAdrian Prantl     }
1384aa2b3a3SAdrian Prantl   };
1394aa2b3a3SAdrian Prantl 
140bc068586SAdrian Prantl public:
PCHContainerGenerator(CompilerInstance & CI,const std::string & MainFileName,const std::string & OutputFileName,std::unique_ptr<raw_pwrite_stream> OS,std::shared_ptr<PCHBuffer> Buffer)1411e63b2bdSAdrian Prantl   PCHContainerGenerator(CompilerInstance &CI, const std::string &MainFileName,
1425a88e1a8SAdrian Prantl                         const std::string &OutputFileName,
14303f8907fSPeter Collingbourne                         std::unique_ptr<raw_pwrite_stream> OS,
1445a88e1a8SAdrian Prantl                         std::shared_ptr<PCHBuffer> Buffer)
145aa5d08d0SAdrian Prantl       : Diags(CI.getDiagnostics()), MainFileName(MainFileName),
146aa5d08d0SAdrian Prantl         OutputFileName(OutputFileName), Ctx(nullptr),
1479402cef0SAdrian Prantl         MMap(CI.getPreprocessor().getHeaderSearchInfo().getModuleMap()),
148*8dfaecc4SArgyrios Kyrtzidis         FS(&CI.getVirtualFileSystem()),
1491e63b2bdSAdrian Prantl         HeaderSearchOpts(CI.getHeaderSearchOpts()),
1500391406eSAdrian Prantl         PreprocessorOpts(CI.getPreprocessorOpts()),
15103f8907fSPeter Collingbourne         TargetOpts(CI.getTargetOpts()), LangOpts(CI.getLangOpts()),
15203f8907fSPeter Collingbourne         OS(std::move(OS)), Buffer(std::move(Buffer)) {
153bc068586SAdrian Prantl     // The debug info output isn't affected by CodeModel and
154bc068586SAdrian Prantl     // ThreadModel, but the backend expects them to be nonempty.
155bc068586SAdrian Prantl     CodeGenOpts.CodeModel = "default";
15615a3ae1aSZequan Wu     LangOpts.setThreadModel(LangOptions::ThreadModelKind::Single);
1576b21ab21SAdrian Prantl     CodeGenOpts.DebugTypeExtRefs = true;
1589a1a1aa2SAdrian Prantl     // When building a module MainFileName is the name of the modulemap file.
1599a1a1aa2SAdrian Prantl     CodeGenOpts.MainFileName =
1609a1a1aa2SAdrian Prantl         LangOpts.CurrentModule.empty() ? MainFileName : LangOpts.CurrentModule;
1618c30592eSBenjamin Kramer     CodeGenOpts.setDebugInfo(codegenoptions::FullDebugInfo);
162af09f4acSDavid Blaikie     CodeGenOpts.setDebuggerTuning(CI.getCodeGenOpts().getDebuggerTuning());
16355fcb4e9SAdrian Prantl     CodeGenOpts.DebugPrefixMap =
16455fcb4e9SAdrian Prantl         CI.getInvocation().getCodeGenOpts().DebugPrefixMap;
165eb200e58SAdrian Prantl     CodeGenOpts.DebugStrictDwarf = CI.getCodeGenOpts().DebugStrictDwarf;
166bc068586SAdrian Prantl   }
167bc068586SAdrian Prantl 
1687eb5464bSHans Wennborg   ~PCHContainerGenerator() override = default;
169bc068586SAdrian Prantl 
Initialize(ASTContext & Context)170bc068586SAdrian Prantl   void Initialize(ASTContext &Context) override {
171293534b1SRichard Smith     assert(!Ctx && "initialized multiple times");
1720f99d6a4SRichard Smith 
173bc068586SAdrian Prantl     Ctx = &Context;
174bc068586SAdrian Prantl     VMContext.reset(new llvm::LLVMContext());
175bc068586SAdrian Prantl     M.reset(new llvm::Module(MainFileName, *VMContext));
1760f1137baSNico Weber     M->setDataLayout(Ctx->getTargetInfo().getDataLayoutString());
177ca3cf9e6SMehdi Amini     Builder.reset(new CodeGen::CodeGenModule(
178*8dfaecc4SArgyrios Kyrtzidis         *Ctx, FS, HeaderSearchOpts, PreprocessorOpts, CodeGenOpts, *M, Diags));
1793a2d4947SAdrian Prantl 
1803a2d4947SAdrian Prantl     // Prepare CGDebugInfo to emit debug info for a clang module.
1813a2d4947SAdrian Prantl     auto *DI = Builder->getModuleDebugInfo();
1823a2d4947SAdrian Prantl     StringRef ModuleName = llvm::sys::path::filename(MainFileName);
183e87e55edSDaniel Grumberg     DI->setPCHDescriptor(
184e87e55edSDaniel Grumberg         {ModuleName, "", OutputFileName, ASTFileSignature::createDISentinel()});
1853a2d4947SAdrian Prantl     DI->setModuleMap(MMap);
186bc068586SAdrian Prantl   }
187bc068586SAdrian Prantl 
HandleTopLevelDecl(DeclGroupRef D)1884aa2b3a3SAdrian Prantl   bool HandleTopLevelDecl(DeclGroupRef D) override {
189abdd6fc4SAdrian Prantl     if (Diags.hasErrorOccurred())
1904aa2b3a3SAdrian Prantl       return true;
1914aa2b3a3SAdrian Prantl 
1924aa2b3a3SAdrian Prantl     // Collect debug info for all decls in this group.
1934aa2b3a3SAdrian Prantl     for (auto *I : D)
1944aa2b3a3SAdrian Prantl       if (!I->isFromASTFile()) {
195cd975018SAdrian Prantl         DebugTypeVisitor DTV(*Builder->getModuleDebugInfo(), *Ctx);
1964aa2b3a3SAdrian Prantl         DTV.TraverseDecl(I);
1974aa2b3a3SAdrian Prantl       }
1984aa2b3a3SAdrian Prantl     return true;
1994aa2b3a3SAdrian Prantl   }
2004aa2b3a3SAdrian Prantl 
HandleTopLevelDeclInObjCContainer(DeclGroupRef D)201d43fe0bdSAdrian Prantl   void HandleTopLevelDeclInObjCContainer(DeclGroupRef D) override {
202d43fe0bdSAdrian Prantl     HandleTopLevelDecl(D);
203d43fe0bdSAdrian Prantl   }
204d43fe0bdSAdrian Prantl 
HandleTagDeclDefinition(TagDecl * D)2054aa2b3a3SAdrian Prantl   void HandleTagDeclDefinition(TagDecl *D) override {
2064aa2b3a3SAdrian Prantl     if (Diags.hasErrorOccurred())
2074aa2b3a3SAdrian Prantl       return;
2084aa2b3a3SAdrian Prantl 
209b3b821f1SAdrian Prantl     if (D->isFromASTFile())
210b3b821f1SAdrian Prantl       return;
211b3b821f1SAdrian Prantl 
212e5238d2aSAdrian Prantl     // Anonymous tag decls are deferred until we are building their declcontext.
213e5238d2aSAdrian Prantl     if (D->getName().empty())
214e5238d2aSAdrian Prantl       return;
215e5238d2aSAdrian Prantl 
2165a9a4277SAdrian Prantl     // Defer tag decls until their declcontext is complete.
2175a9a4277SAdrian Prantl     auto *DeclCtx = D->getDeclContext();
2185a9a4277SAdrian Prantl     while (DeclCtx) {
2195a9a4277SAdrian Prantl       if (auto *D = dyn_cast<TagDecl>(DeclCtx))
2205a9a4277SAdrian Prantl         if (!D->isCompleteDefinition())
2215a9a4277SAdrian Prantl           return;
2225a9a4277SAdrian Prantl       DeclCtx = DeclCtx->getParent();
2235a9a4277SAdrian Prantl     }
2245a9a4277SAdrian Prantl 
225cd975018SAdrian Prantl     DebugTypeVisitor DTV(*Builder->getModuleDebugInfo(), *Ctx);
226b3b821f1SAdrian Prantl     DTV.TraverseDecl(D);
2274aa2b3a3SAdrian Prantl     Builder->UpdateCompletedType(D);
2284aa2b3a3SAdrian Prantl   }
2294aa2b3a3SAdrian Prantl 
HandleTagDeclRequiredDefinition(const TagDecl * D)2304aa2b3a3SAdrian Prantl   void HandleTagDeclRequiredDefinition(const TagDecl *D) override {
2314aa2b3a3SAdrian Prantl     if (Diags.hasErrorOccurred())
2324aa2b3a3SAdrian Prantl       return;
2334aa2b3a3SAdrian Prantl 
2344aa2b3a3SAdrian Prantl     if (const RecordDecl *RD = dyn_cast<RecordDecl>(D))
2358bd4c13fSAdrian Prantl       Builder->getModuleDebugInfo()->completeRequiredType(RD);
2364aa2b3a3SAdrian Prantl   }
2374aa2b3a3SAdrian Prantl 
HandleImplicitImportDecl(ImportDecl * D)238c5e3647fSAdrian Prantl   void HandleImplicitImportDecl(ImportDecl *D) override {
239c5e3647fSAdrian Prantl     if (!D->getImportedOwningModule())
240c5e3647fSAdrian Prantl       Builder->getModuleDebugInfo()->EmitImportDecl(*D);
241c5e3647fSAdrian Prantl   }
242c5e3647fSAdrian Prantl 
243bc068586SAdrian Prantl   /// Emit a container holding the serialized AST.
HandleTranslationUnit(ASTContext & Ctx)244bc068586SAdrian Prantl   void HandleTranslationUnit(ASTContext &Ctx) override {
245bc068586SAdrian Prantl     assert(M && VMContext && Builder);
246bc068586SAdrian Prantl     // Delete these on function exit.
247bc068586SAdrian Prantl     std::unique_ptr<llvm::LLVMContext> VMContext = std::move(this->VMContext);
248bc068586SAdrian Prantl     std::unique_ptr<llvm::Module> M = std::move(this->M);
249bc068586SAdrian Prantl     std::unique_ptr<CodeGen::CodeGenModule> Builder = std::move(this->Builder);
250bc068586SAdrian Prantl 
251bc068586SAdrian Prantl     if (Diags.hasErrorOccurred())
252bc068586SAdrian Prantl       return;
253bc068586SAdrian Prantl 
254bc068586SAdrian Prantl     M->setTargetTriple(Ctx.getTargetInfo().getTriple().getTriple());
2550f1137baSNico Weber     M->setDataLayout(Ctx.getTargetInfo().getDataLayoutString());
256c96da8faSAdrian Prantl 
257c96da8faSAdrian Prantl     // PCH files don't have a signature field in the control block,
258c96da8faSAdrian Prantl     // but LLVM detects DWO CUs by looking for a non-zero DWO id.
25960fa2888SDuncan P. N. Exon Smith     // We use the lower 64 bits for debug info.
260105151caSRaphael Isemann 
26160fa2888SDuncan P. N. Exon Smith     uint64_t Signature =
262105151caSRaphael Isemann         Buffer->Signature ? Buffer->Signature.truncatedValue() : ~1ULL;
263105151caSRaphael Isemann 
264c96da8faSAdrian Prantl     Builder->getModuleDebugInfo()->setDwoId(Signature);
265bc068586SAdrian Prantl 
266bc068586SAdrian Prantl     // Finalize the Builder.
267bc068586SAdrian Prantl     if (Builder)
268bc068586SAdrian Prantl       Builder->Release();
269bc068586SAdrian Prantl 
270bc068586SAdrian Prantl     // Ensure the target exists.
271bc068586SAdrian Prantl     std::string Error;
272bc068586SAdrian Prantl     auto Triple = Ctx.getTargetInfo().getTriple();
273bc068586SAdrian Prantl     if (!llvm::TargetRegistry::lookupTarget(Triple.getTriple(), Error))
274b9b90bb5SSimon Pilgrim       llvm::report_fatal_error(llvm::Twine(Error));
275bc068586SAdrian Prantl 
276bc068586SAdrian Prantl     // Emit the serialized Clang AST into its own section.
277bc068586SAdrian Prantl     assert(Buffer->IsComplete && "serialization did not complete");
278bc068586SAdrian Prantl     auto &SerializedAST = Buffer->Data;
279bc068586SAdrian Prantl     auto Size = SerializedAST.size();
2801813fde9SYuta Saito 
2811813fde9SYuta Saito     if (Triple.isOSBinFormatWasm()) {
2821813fde9SYuta Saito       // Emit __clangast in custom section instead of named data segment
2831813fde9SYuta Saito       // to find it while iterating sections.
2841813fde9SYuta Saito       // This could be avoided if all data segements (the wasm sense) were
2851813fde9SYuta Saito       // represented as their own sections (in the llvm sense).
2861813fde9SYuta Saito       // TODO: https://github.com/WebAssembly/tool-conventions/issues/138
2871813fde9SYuta Saito       llvm::NamedMDNode *MD =
2881813fde9SYuta Saito           M->getOrInsertNamedMetadata("wasm.custom_sections");
2891813fde9SYuta Saito       llvm::Metadata *Ops[2] = {
2901813fde9SYuta Saito           llvm::MDString::get(*VMContext, "__clangast"),
2911813fde9SYuta Saito           llvm::MDString::get(*VMContext,
2921813fde9SYuta Saito                               StringRef(SerializedAST.data(), Size))};
2931813fde9SYuta Saito       auto *NameAndContent = llvm::MDTuple::get(*VMContext, Ops);
2941813fde9SYuta Saito       MD->addOperand(NameAndContent);
2951813fde9SYuta Saito     } else {
296bc068586SAdrian Prantl       auto Int8Ty = llvm::Type::getInt8Ty(*VMContext);
297bc068586SAdrian Prantl       auto *Ty = llvm::ArrayType::get(Int8Ty, Size);
2985a88e1a8SAdrian Prantl       auto *Data = llvm::ConstantDataArray::getString(
2995a88e1a8SAdrian Prantl           *VMContext, StringRef(SerializedAST.data(), Size),
300bc068586SAdrian Prantl           /*AddNull=*/false);
301bc068586SAdrian Prantl       auto *ASTSym = new llvm::GlobalVariable(
3021813fde9SYuta Saito           *M, Ty, /*constant*/ true, llvm::GlobalVariable::InternalLinkage,
3031813fde9SYuta Saito           Data, "__clang_ast");
304bc068586SAdrian Prantl       // The on-disk hashtable needs to be aligned.
305c79099e0SGuillaume Chatelet       ASTSym->setAlignment(llvm::Align(8));
306bc068586SAdrian Prantl 
307bc068586SAdrian Prantl       // Mach-O also needs a segment name.
308bc068586SAdrian Prantl       if (Triple.isOSBinFormatMachO())
309bc068586SAdrian Prantl         ASTSym->setSection("__CLANG,__clangast");
310bc068586SAdrian Prantl       // COFF has an eight character length limit.
311bc068586SAdrian Prantl       else if (Triple.isOSBinFormatCOFF())
312bc068586SAdrian Prantl         ASTSym->setSection("clangast");
313bc068586SAdrian Prantl       else
314bc068586SAdrian Prantl         ASTSym->setSection("__clangast");
3151813fde9SYuta Saito     }
316bc068586SAdrian Prantl 
3173538b39eSNicola Zaghen     LLVM_DEBUG({
318bc068586SAdrian Prantl       // Print the IR for the PCH container to the debug output.
319bc068586SAdrian Prantl       llvm::SmallString<0> Buffer;
32003f8907fSPeter Collingbourne       clang::EmitBackendOutput(
321888e289eSSaleem Abdulrasool           Diags, HeaderSearchOpts, CodeGenOpts, TargetOpts, LangOpts,
3220f1137baSNico Weber           Ctx.getTargetInfo().getDataLayoutString(), M.get(),
32303f8907fSPeter Collingbourne           BackendAction::Backend_EmitLL,
3242b3d49b6SJonas Devlieghere           std::make_unique<llvm::raw_svector_ostream>(Buffer));
325bc068586SAdrian Prantl       llvm::dbgs() << Buffer;
326bc068586SAdrian Prantl     });
327bc068586SAdrian Prantl 
328bc068586SAdrian Prantl     // Use the LLVM backend to emit the pch container.
329888e289eSSaleem Abdulrasool     clang::EmitBackendOutput(Diags, HeaderSearchOpts, CodeGenOpts, TargetOpts,
3300f1137baSNico Weber                              LangOpts,
3310f1137baSNico Weber                              Ctx.getTargetInfo().getDataLayoutString(), M.get(),
3320f1137baSNico Weber                              BackendAction::Backend_EmitObj, std::move(OS));
333bc068586SAdrian Prantl 
334bc068586SAdrian Prantl     // Free the memory for the temporary buffer.
335bc068586SAdrian Prantl     llvm::SmallVector<char, 0> Empty;
336bc068586SAdrian Prantl     SerializedAST = std::move(Empty);
337bc068586SAdrian Prantl   }
338bc068586SAdrian Prantl };
3395a88e1a8SAdrian Prantl 
3407eb5464bSHans Wennborg } // anonymous namespace
341bc068586SAdrian Prantl 
342bc068586SAdrian Prantl 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) const343fb2398d0SAdrian Prantl ObjectFilePCHContainerWriter::CreatePCHContainerGenerator(
3441e63b2bdSAdrian Prantl     CompilerInstance &CI, const std::string &MainFileName,
34503f8907fSPeter Collingbourne     const std::string &OutputFileName,
34603f8907fSPeter Collingbourne     std::unique_ptr<llvm::raw_pwrite_stream> OS,
3471e63b2bdSAdrian Prantl     std::shared_ptr<PCHBuffer> Buffer) const {
3482b3d49b6SJonas Devlieghere   return std::make_unique<PCHContainerGenerator>(
34903f8907fSPeter Collingbourne       CI, MainFileName, OutputFileName, std::move(OS), Buffer);
350bc068586SAdrian Prantl }
351bc068586SAdrian Prantl 
35277c89b69SPeter Collingbourne StringRef
ExtractPCH(llvm::MemoryBufferRef Buffer) const35377c89b69SPeter Collingbourne ObjectFilePCHContainerReader::ExtractPCH(llvm::MemoryBufferRef Buffer) const {
35477c89b69SPeter Collingbourne   StringRef PCH;
355576b2dbeSAdrian Prantl   auto OFOrErr = llvm::object::ObjectFile::createObjectFile(Buffer);
356576b2dbeSAdrian Prantl   if (OFOrErr) {
357576b2dbeSAdrian Prantl     auto &OF = OFOrErr.get();
358576b2dbeSAdrian Prantl     bool IsCOFF = isa<llvm::object::COFFObjectFile>(*OF);
359bc068586SAdrian Prantl     // Find the clang AST section in the container.
360576b2dbeSAdrian Prantl     for (auto &Section : OF->sections()) {
361bc068586SAdrian Prantl       StringRef Name;
362a11d302fSGeorge Rimar       if (Expected<StringRef> NameOrErr = Section.getName())
363a11d302fSGeorge Rimar         Name = *NameOrErr;
364a11d302fSGeorge Rimar       else
365a11d302fSGeorge Rimar         consumeError(NameOrErr.takeError());
366a11d302fSGeorge Rimar 
367576b2dbeSAdrian Prantl       if ((!IsCOFF && Name == "__clangast") || (IsCOFF && Name == "clangast")) {
368e183340cSFangrui Song         if (Expected<StringRef> E = Section.getContents())
369e183340cSFangrui Song           return *E;
370e183340cSFangrui Song         else {
371e183340cSFangrui Song           handleAllErrors(E.takeError(), [&](const llvm::ErrorInfoBase &EIB) {
372e183340cSFangrui Song             EIB.log(llvm::errs());
373e183340cSFangrui Song           });
374e183340cSFangrui Song           return "";
375e183340cSFangrui Song         }
376bc068586SAdrian Prantl       }
377bc068586SAdrian Prantl     }
378bc068586SAdrian Prantl   }
379576b2dbeSAdrian Prantl   handleAllErrors(OFOrErr.takeError(), [&](const llvm::ErrorInfoBase &EIB) {
380576b2dbeSAdrian Prantl     if (EIB.convertToErrorCode() ==
381576b2dbeSAdrian Prantl         llvm::object::object_error::invalid_file_type)
382bc068586SAdrian Prantl       // As a fallback, treat the buffer as a raw AST.
38377c89b69SPeter Collingbourne       PCH = Buffer.getBuffer();
384576b2dbeSAdrian Prantl     else
385576b2dbeSAdrian Prantl       EIB.log(llvm::errs());
386576b2dbeSAdrian Prantl   });
38777c89b69SPeter Collingbourne   return PCH;
388bc068586SAdrian Prantl }
389