1 //===--- ObjectFilePCHContainerOperations.cpp -----------------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 
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/Serialization/ASTWriter.h"
23 #include "llvm/ADT/StringRef.h"
24 #include "llvm/Bitcode/BitstreamReader.h"
25 #include "llvm/DebugInfo/DWARF/DWARFContext.h"
26 #include "llvm/IR/Constants.h"
27 #include "llvm/IR/DataLayout.h"
28 #include "llvm/IR/LLVMContext.h"
29 #include "llvm/IR/Module.h"
30 #include "llvm/Object/COFF.h"
31 #include "llvm/Object/ObjectFile.h"
32 #include "llvm/Support/TargetRegistry.h"
33 #include <memory>
34 
35 using namespace clang;
36 
37 #define DEBUG_TYPE "pchcontainer"
38 
39 namespace {
40 class PCHContainerGenerator : public ASTConsumer {
41   DiagnosticsEngine &Diags;
42   const std::string MainFileName;
43   ASTContext *Ctx;
44   const HeaderSearchOptions &HeaderSearchOpts;
45   const PreprocessorOptions &PreprocessorOpts;
46   CodeGenOptions CodeGenOpts;
47   const TargetOptions TargetOpts;
48   const LangOptions LangOpts;
49   std::unique_ptr<llvm::LLVMContext> VMContext;
50   std::unique_ptr<llvm::Module> M;
51   std::unique_ptr<CodeGen::CodeGenModule> Builder;
52   raw_pwrite_stream *OS;
53   std::shared_ptr<PCHBuffer> Buffer;
54 
55   /// Visit every type and emit debug info for it.
56   struct DebugTypeVisitor : public RecursiveASTVisitor<DebugTypeVisitor> {
57     clang::CodeGen::CGDebugInfo &DI;
58     ASTContext &Ctx;
59     DebugTypeVisitor(clang::CodeGen::CGDebugInfo &DI, ASTContext &Ctx)
60         : DI(DI), Ctx(Ctx) {}
61 
62     /// Determine whether this type can be represented in DWARF.
63     static bool CanRepresent(const Type *Ty) {
64       return !Ty->isDependentType() && !Ty->isUndeducedType();
65     }
66 
67     bool VisitTypeDecl(TypeDecl *D) {
68       QualType QualTy = Ctx.getTypeDeclType(D);
69       if (!QualTy.isNull() && CanRepresent(QualTy.getTypePtr()))
70         DI.getOrCreateStandaloneType(QualTy, D->getLocation());
71       return true;
72     }
73 
74     bool VisitObjCInterfaceDecl(ObjCInterfaceDecl *D) {
75       QualType QualTy(D->getTypeForDecl(), 0);
76       if (!QualTy.isNull() && CanRepresent(QualTy.getTypePtr()))
77         DI.getOrCreateStandaloneType(QualTy, D->getLocation());
78       return true;
79     }
80 
81     bool VisitFunctionDecl(FunctionDecl *D) {
82       if (isa<CXXMethodDecl>(D))
83         // This is not yet supported. Constructing the `this' argument
84         // mandates a CodeGenFunction.
85         return true;
86 
87       SmallVector<QualType, 16> ArgTypes;
88       for (auto i : D->params())
89         ArgTypes.push_back(i->getType());
90       QualType RetTy = D->getReturnType();
91       QualType FnTy = Ctx.getFunctionType(RetTy, ArgTypes,
92                                           FunctionProtoType::ExtProtoInfo());
93       if (CanRepresent(FnTy.getTypePtr()))
94         DI.EmitFunctionDecl(D, D->getLocation(), FnTy);
95       return true;
96     }
97 
98     bool VisitObjCMethodDecl(ObjCMethodDecl *D) {
99       if (!D->getClassInterface())
100         return true;
101 
102       bool selfIsPseudoStrong, selfIsConsumed;
103       SmallVector<QualType, 16> ArgTypes;
104       ArgTypes.push_back(D->getSelfType(Ctx, D->getClassInterface(),
105                                         selfIsPseudoStrong, selfIsConsumed));
106       ArgTypes.push_back(Ctx.getObjCSelType());
107       for (auto i : D->params())
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);
114       return true;
115     }
116   };
117 
118 public:
119   PCHContainerGenerator(DiagnosticsEngine &diags, const CompilerInstance &CI,
120                         const std::string &MainFileName,
121                         const std::string &OutputFileName,
122                         raw_pwrite_stream *OS,
123                         std::shared_ptr<PCHBuffer> Buffer)
124       : Diags(diags), Ctx(nullptr), HeaderSearchOpts(CI.getHeaderSearchOpts()),
125         PreprocessorOpts(CI.getPreprocessorOpts()),
126         TargetOpts(CI.getTargetOpts()), LangOpts(CI.getLangOpts()), OS(OS),
127         Buffer(Buffer) {
128     // The debug info output isn't affected by CodeModel and
129     // ThreadModel, but the backend expects them to be nonempty.
130     CodeGenOpts.CodeModel = "default";
131     CodeGenOpts.ThreadModel = "single";
132     CodeGenOpts.DebugTypeExtRefs = true;
133     CodeGenOpts.setDebugInfo(CodeGenOptions::FullDebugInfo);
134     CodeGenOpts.SplitDwarfFile = OutputFileName;
135   }
136 
137   ~PCHContainerGenerator() override = default;
138 
139   void Initialize(ASTContext &Context) override {
140     assert(!Ctx && "initialized multiple times");
141 
142     Ctx = &Context;
143     VMContext.reset(new llvm::LLVMContext());
144     M.reset(new llvm::Module(MainFileName, *VMContext));
145     M->setDataLayout(Ctx->getTargetInfo().getDataLayoutString());
146     Builder.reset(new CodeGen::CodeGenModule(
147         *Ctx, HeaderSearchOpts, PreprocessorOpts, CodeGenOpts, *M, Diags));
148   }
149 
150   bool HandleTopLevelDecl(DeclGroupRef D) override {
151     if (Diags.hasErrorOccurred() ||
152         (CodeGenOpts.getDebugInfo() == CodeGenOptions::NoDebugInfo))
153       return true;
154 
155     // Collect debug info for all decls in this group.
156     for (auto *I : D)
157       if (!I->isFromASTFile()) {
158         DebugTypeVisitor DTV(*Builder->getModuleDebugInfo(), *Ctx);
159         DTV.TraverseDecl(I);
160       }
161     return true;
162   }
163 
164   void HandleTagDeclDefinition(TagDecl *D) override {
165     if (Diags.hasErrorOccurred())
166       return;
167 
168     Builder->UpdateCompletedType(D);
169   }
170 
171   void HandleTagDeclRequiredDefinition(const TagDecl *D) override {
172     if (Diags.hasErrorOccurred())
173       return;
174 
175     if (CodeGen::CGDebugInfo *DI = Builder->getModuleDebugInfo())
176       if (const RecordDecl *RD = dyn_cast<RecordDecl>(D))
177         DI->completeRequiredType(RD);
178   }
179 
180   /// Emit a container holding the serialized AST.
181   void HandleTranslationUnit(ASTContext &Ctx) override {
182     assert(M && VMContext && Builder);
183     // Delete these on function exit.
184     std::unique_ptr<llvm::LLVMContext> VMContext = std::move(this->VMContext);
185     std::unique_ptr<llvm::Module> M = std::move(this->M);
186     std::unique_ptr<CodeGen::CodeGenModule> Builder = std::move(this->Builder);
187 
188     if (Diags.hasErrorOccurred())
189       return;
190 
191     M->setTargetTriple(Ctx.getTargetInfo().getTriple().getTriple());
192     M->setDataLayout(Ctx.getTargetInfo().getDataLayoutString());
193 
194     // Finalize the Builder.
195     if (Builder)
196       Builder->Release();
197 
198     // Ensure the target exists.
199     std::string Error;
200     auto Triple = Ctx.getTargetInfo().getTriple();
201     if (!llvm::TargetRegistry::lookupTarget(Triple.getTriple(), Error))
202       llvm::report_fatal_error(Error);
203 
204     // Emit the serialized Clang AST into its own section.
205     assert(Buffer->IsComplete && "serialization did not complete");
206     auto &SerializedAST = Buffer->Data;
207     auto Size = SerializedAST.size();
208     auto Int8Ty = llvm::Type::getInt8Ty(*VMContext);
209     auto *Ty = llvm::ArrayType::get(Int8Ty, Size);
210     auto *Data = llvm::ConstantDataArray::getString(
211         *VMContext, StringRef(SerializedAST.data(), Size),
212         /*AddNull=*/false);
213     auto *ASTSym = new llvm::GlobalVariable(
214         *M, Ty, /*constant*/ true, llvm::GlobalVariable::InternalLinkage, Data,
215         "__clang_ast");
216     // The on-disk hashtable needs to be aligned.
217     ASTSym->setAlignment(8);
218 
219     // Mach-O also needs a segment name.
220     if (Triple.isOSBinFormatMachO())
221       ASTSym->setSection("__CLANG,__clangast");
222     // COFF has an eight character length limit.
223     else if (Triple.isOSBinFormatCOFF())
224       ASTSym->setSection("clangast");
225     else
226       ASTSym->setSection("__clangast");
227 
228     DEBUG({
229       // Print the IR for the PCH container to the debug output.
230       llvm::SmallString<0> Buffer;
231       llvm::raw_svector_ostream OS(Buffer);
232       clang::EmitBackendOutput(Diags, CodeGenOpts, TargetOpts, LangOpts,
233                                Ctx.getTargetInfo().getDataLayoutString(),
234                                M.get(), BackendAction::Backend_EmitLL, &OS);
235       llvm::dbgs() << Buffer;
236     });
237 
238     // Use the LLVM backend to emit the pch container.
239     clang::EmitBackendOutput(Diags, CodeGenOpts, TargetOpts, LangOpts,
240                              Ctx.getTargetInfo().getDataLayoutString(),
241                              M.get(), BackendAction::Backend_EmitObj, OS);
242 
243     // Make sure the pch container hits disk.
244     OS->flush();
245 
246     // Free the memory for the temporary buffer.
247     llvm::SmallVector<char, 0> Empty;
248     SerializedAST = std::move(Empty);
249   }
250 };
251 
252 } // anonymous namespace
253 
254 std::unique_ptr<ASTConsumer>
255 ObjectFilePCHContainerWriter::CreatePCHContainerGenerator(
256     DiagnosticsEngine &Diags, const CompilerInstance &CI,
257     const std::string &MainFileName, const std::string &OutputFileName,
258     llvm::raw_pwrite_stream *OS, std::shared_ptr<PCHBuffer> Buffer) const {
259   return llvm::make_unique<PCHContainerGenerator>(Diags, CI, MainFileName,
260                                                   OutputFileName, OS, Buffer);
261 }
262 
263 void ObjectFilePCHContainerReader::ExtractPCH(
264     llvm::MemoryBufferRef Buffer, llvm::BitstreamReader &StreamFile) const {
265   if (auto OF = llvm::object::ObjectFile::createObjectFile(Buffer)) {
266     auto *Obj = OF.get().get();
267     bool IsCOFF = isa<llvm::object::COFFObjectFile>(Obj);
268     // Find the clang AST section in the container.
269     for (auto &Section : OF->get()->sections()) {
270       StringRef Name;
271       Section.getName(Name);
272       if ((!IsCOFF && Name == "__clangast") ||
273           ( IsCOFF && Name ==   "clangast")) {
274         StringRef Buf;
275         Section.getContents(Buf);
276         StreamFile.init((const unsigned char *)Buf.begin(),
277                         (const unsigned char *)Buf.end());
278         return;
279       }
280     }
281   }
282 
283   // As a fallback, treat the buffer as a raw AST.
284   StreamFile.init((const unsigned char *)Buffer.getBufferStart(),
285                   (const unsigned char *)Buffer.getBufferEnd());
286 }
287