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/Lex/HeaderSearch.h" 23 #include "clang/Lex/Preprocessor.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/Path.h" 35 #include "llvm/Support/TargetRegistry.h" 36 #include <memory> 37 #include <utility> 38 39 using namespace clang; 40 41 #define DEBUG_TYPE "pchcontainer" 42 43 namespace { 44 class PCHContainerGenerator : public ASTConsumer { 45 DiagnosticsEngine &Diags; 46 const std::string MainFileName; 47 const std::string OutputFileName; 48 ASTContext *Ctx; 49 ModuleMap &MMap; 50 const HeaderSearchOptions &HeaderSearchOpts; 51 const PreprocessorOptions &PreprocessorOpts; 52 CodeGenOptions CodeGenOpts; 53 const TargetOptions TargetOpts; 54 const LangOptions LangOpts; 55 std::unique_ptr<llvm::LLVMContext> VMContext; 56 std::unique_ptr<llvm::Module> M; 57 std::unique_ptr<CodeGen::CodeGenModule> Builder; 58 std::unique_ptr<raw_pwrite_stream> OS; 59 std::shared_ptr<PCHBuffer> Buffer; 60 61 /// Visit every type and emit debug info for it. 62 struct DebugTypeVisitor : public RecursiveASTVisitor<DebugTypeVisitor> { 63 clang::CodeGen::CGDebugInfo &DI; 64 ASTContext &Ctx; 65 DebugTypeVisitor(clang::CodeGen::CGDebugInfo &DI, ASTContext &Ctx) 66 : DI(DI), Ctx(Ctx) {} 67 68 /// Determine whether this type can be represented in DWARF. 69 static bool CanRepresent(const Type *Ty) { 70 return !Ty->isDependentType() && !Ty->isUndeducedType(); 71 } 72 73 bool VisitImportDecl(ImportDecl *D) { 74 if (!D->getImportedOwningModule()) 75 DI.EmitImportDecl(*D); 76 return true; 77 } 78 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 (auto *TD = dyn_cast<TagDecl>(D)) 84 if (!TD->isCompleteDefinition()) 85 return true; 86 87 QualType QualTy = Ctx.getTypeDeclType(D); 88 if (!QualTy.isNull() && CanRepresent(QualTy.getTypePtr())) 89 DI.getOrCreateStandaloneType(QualTy, D->getLocation()); 90 return true; 91 } 92 93 bool VisitObjCInterfaceDecl(ObjCInterfaceDecl *D) { 94 QualType QualTy(D->getTypeForDecl(), 0); 95 if (!QualTy.isNull() && CanRepresent(QualTy.getTypePtr())) 96 DI.getOrCreateStandaloneType(QualTy, D->getLocation()); 97 return true; 98 } 99 100 bool VisitFunctionDecl(FunctionDecl *D) { 101 if (isa<CXXMethodDecl>(D)) 102 // This is not yet supported. Constructing the `this' argument 103 // mandates a CodeGenFunction. 104 return true; 105 106 SmallVector<QualType, 16> ArgTypes; 107 for (auto i : D->parameters()) 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 bool VisitObjCMethodDecl(ObjCMethodDecl *D) { 118 if (!D->getClassInterface()) 119 return true; 120 121 bool selfIsPseudoStrong, selfIsConsumed; 122 SmallVector<QualType, 16> ArgTypes; 123 ArgTypes.push_back(D->getSelfType(Ctx, D->getClassInterface(), 124 selfIsPseudoStrong, selfIsConsumed)); 125 ArgTypes.push_back(Ctx.getObjCSelType()); 126 for (auto i : D->parameters()) 127 ArgTypes.push_back(i->getType()); 128 QualType RetTy = D->getReturnType(); 129 QualType FnTy = Ctx.getFunctionType(RetTy, ArgTypes, 130 FunctionProtoType::ExtProtoInfo()); 131 if (CanRepresent(FnTy.getTypePtr())) 132 DI.EmitFunctionDecl(D, D->getLocation(), FnTy); 133 return true; 134 } 135 }; 136 137 public: 138 PCHContainerGenerator(CompilerInstance &CI, const std::string &MainFileName, 139 const std::string &OutputFileName, 140 std::unique_ptr<raw_pwrite_stream> OS, 141 std::shared_ptr<PCHBuffer> Buffer) 142 : Diags(CI.getDiagnostics()), MainFileName(MainFileName), 143 OutputFileName(OutputFileName), Ctx(nullptr), 144 MMap(CI.getPreprocessor().getHeaderSearchInfo().getModuleMap()), 145 HeaderSearchOpts(CI.getHeaderSearchOpts()), 146 PreprocessorOpts(CI.getPreprocessorOpts()), 147 TargetOpts(CI.getTargetOpts()), LangOpts(CI.getLangOpts()), 148 OS(std::move(OS)), Buffer(std::move(Buffer)) { 149 // The debug info output isn't affected by CodeModel and 150 // ThreadModel, but the backend expects them to be nonempty. 151 CodeGenOpts.CodeModel = "default"; 152 CodeGenOpts.ThreadModel = "single"; 153 CodeGenOpts.DebugTypeExtRefs = true; 154 // When building a module MainFileName is the name of the modulemap file. 155 CodeGenOpts.MainFileName = 156 LangOpts.CurrentModule.empty() ? MainFileName : LangOpts.CurrentModule; 157 CodeGenOpts.setDebugInfo(codegenoptions::FullDebugInfo); 158 CodeGenOpts.setDebuggerTuning(CI.getCodeGenOpts().getDebuggerTuning()); 159 CodeGenOpts.DebugPrefixMap = 160 CI.getInvocation().getCodeGenOpts().DebugPrefixMap; 161 } 162 163 ~PCHContainerGenerator() override = default; 164 165 void Initialize(ASTContext &Context) override { 166 assert(!Ctx && "initialized multiple times"); 167 168 Ctx = &Context; 169 VMContext.reset(new llvm::LLVMContext()); 170 M.reset(new llvm::Module(MainFileName, *VMContext)); 171 M->setDataLayout(Ctx->getTargetInfo().getDataLayout()); 172 Builder.reset(new CodeGen::CodeGenModule( 173 *Ctx, HeaderSearchOpts, PreprocessorOpts, CodeGenOpts, *M, Diags)); 174 175 // Prepare CGDebugInfo to emit debug info for a clang module. 176 auto *DI = Builder->getModuleDebugInfo(); 177 StringRef ModuleName = llvm::sys::path::filename(MainFileName); 178 DI->setPCHDescriptor({ModuleName, "", OutputFileName, 179 ASTFileSignature{{{~0U, ~0U, ~0U, ~0U, ~1U}}}}); 180 DI->setModuleMap(MMap); 181 } 182 183 bool HandleTopLevelDecl(DeclGroupRef D) override { 184 if (Diags.hasErrorOccurred()) 185 return true; 186 187 // Collect debug info for all decls in this group. 188 for (auto *I : D) 189 if (!I->isFromASTFile()) { 190 DebugTypeVisitor DTV(*Builder->getModuleDebugInfo(), *Ctx); 191 DTV.TraverseDecl(I); 192 } 193 return true; 194 } 195 196 void HandleTopLevelDeclInObjCContainer(DeclGroupRef D) override { 197 HandleTopLevelDecl(D); 198 } 199 200 void HandleTagDeclDefinition(TagDecl *D) override { 201 if (Diags.hasErrorOccurred()) 202 return; 203 204 if (D->isFromASTFile()) 205 return; 206 207 // Anonymous tag decls are deferred until we are building their declcontext. 208 if (D->getName().empty()) 209 return; 210 211 // Defer tag decls until their declcontext is complete. 212 auto *DeclCtx = D->getDeclContext(); 213 while (DeclCtx) { 214 if (auto *D = dyn_cast<TagDecl>(DeclCtx)) 215 if (!D->isCompleteDefinition()) 216 return; 217 DeclCtx = DeclCtx->getParent(); 218 } 219 220 DebugTypeVisitor DTV(*Builder->getModuleDebugInfo(), *Ctx); 221 DTV.TraverseDecl(D); 222 Builder->UpdateCompletedType(D); 223 } 224 225 void HandleTagDeclRequiredDefinition(const TagDecl *D) override { 226 if (Diags.hasErrorOccurred()) 227 return; 228 229 if (const RecordDecl *RD = dyn_cast<RecordDecl>(D)) 230 Builder->getModuleDebugInfo()->completeRequiredType(RD); 231 } 232 233 void HandleImplicitImportDecl(ImportDecl *D) override { 234 if (!D->getImportedOwningModule()) 235 Builder->getModuleDebugInfo()->EmitImportDecl(*D); 236 } 237 238 /// Emit a container holding the serialized AST. 239 void HandleTranslationUnit(ASTContext &Ctx) override { 240 assert(M && VMContext && Builder); 241 // Delete these on function exit. 242 std::unique_ptr<llvm::LLVMContext> VMContext = std::move(this->VMContext); 243 std::unique_ptr<llvm::Module> M = std::move(this->M); 244 std::unique_ptr<CodeGen::CodeGenModule> Builder = std::move(this->Builder); 245 246 if (Diags.hasErrorOccurred()) 247 return; 248 249 M->setTargetTriple(Ctx.getTargetInfo().getTriple().getTriple()); 250 M->setDataLayout(Ctx.getTargetInfo().getDataLayout()); 251 252 // PCH files don't have a signature field in the control block, 253 // but LLVM detects DWO CUs by looking for a non-zero DWO id. 254 // We use the lower 64 bits for debug info. 255 uint64_t Signature = 256 Buffer->Signature 257 ? (uint64_t)Buffer->Signature[1] << 32 | Buffer->Signature[0] 258 : ~1ULL; 259 Builder->getModuleDebugInfo()->setDwoId(Signature); 260 261 // Finalize the Builder. 262 if (Builder) 263 Builder->Release(); 264 265 // Ensure the target exists. 266 std::string Error; 267 auto Triple = Ctx.getTargetInfo().getTriple(); 268 if (!llvm::TargetRegistry::lookupTarget(Triple.getTriple(), Error)) 269 llvm::report_fatal_error(Error); 270 271 // Emit the serialized Clang AST into its own section. 272 assert(Buffer->IsComplete && "serialization did not complete"); 273 auto &SerializedAST = Buffer->Data; 274 auto Size = SerializedAST.size(); 275 auto Int8Ty = llvm::Type::getInt8Ty(*VMContext); 276 auto *Ty = llvm::ArrayType::get(Int8Ty, Size); 277 auto *Data = llvm::ConstantDataArray::getString( 278 *VMContext, StringRef(SerializedAST.data(), Size), 279 /*AddNull=*/false); 280 auto *ASTSym = new llvm::GlobalVariable( 281 *M, Ty, /*constant*/ true, llvm::GlobalVariable::InternalLinkage, Data, 282 "__clang_ast"); 283 // The on-disk hashtable needs to be aligned. 284 ASTSym->setAlignment(8); 285 286 // Mach-O also needs a segment name. 287 if (Triple.isOSBinFormatMachO()) 288 ASTSym->setSection("__CLANG,__clangast"); 289 // COFF has an eight character length limit. 290 else if (Triple.isOSBinFormatCOFF()) 291 ASTSym->setSection("clangast"); 292 else 293 ASTSym->setSection("__clangast"); 294 295 LLVM_DEBUG({ 296 // Print the IR for the PCH container to the debug output. 297 llvm::SmallString<0> Buffer; 298 clang::EmitBackendOutput( 299 Diags, HeaderSearchOpts, CodeGenOpts, TargetOpts, LangOpts, 300 Ctx.getTargetInfo().getDataLayout(), M.get(), 301 BackendAction::Backend_EmitLL, 302 llvm::make_unique<llvm::raw_svector_ostream>(Buffer)); 303 llvm::dbgs() << Buffer; 304 }); 305 306 // Use the LLVM backend to emit the pch container. 307 clang::EmitBackendOutput(Diags, HeaderSearchOpts, CodeGenOpts, TargetOpts, 308 LangOpts, Ctx.getTargetInfo().getDataLayout(), 309 M.get(), BackendAction::Backend_EmitObj, 310 std::move(OS)); 311 312 // Free the memory for the temporary buffer. 313 llvm::SmallVector<char, 0> Empty; 314 SerializedAST = std::move(Empty); 315 } 316 }; 317 318 } // anonymous namespace 319 320 std::unique_ptr<ASTConsumer> 321 ObjectFilePCHContainerWriter::CreatePCHContainerGenerator( 322 CompilerInstance &CI, const std::string &MainFileName, 323 const std::string &OutputFileName, 324 std::unique_ptr<llvm::raw_pwrite_stream> OS, 325 std::shared_ptr<PCHBuffer> Buffer) const { 326 return llvm::make_unique<PCHContainerGenerator>( 327 CI, MainFileName, OutputFileName, std::move(OS), Buffer); 328 } 329 330 StringRef 331 ObjectFilePCHContainerReader::ExtractPCH(llvm::MemoryBufferRef Buffer) const { 332 StringRef PCH; 333 auto OFOrErr = llvm::object::ObjectFile::createObjectFile(Buffer); 334 if (OFOrErr) { 335 auto &OF = OFOrErr.get(); 336 bool IsCOFF = isa<llvm::object::COFFObjectFile>(*OF); 337 // Find the clang AST section in the container. 338 for (auto &Section : OF->sections()) { 339 StringRef Name; 340 Section.getName(Name); 341 if ((!IsCOFF && Name == "__clangast") || (IsCOFF && Name == "clangast")) { 342 Section.getContents(PCH); 343 return PCH; 344 } 345 } 346 } 347 handleAllErrors(OFOrErr.takeError(), [&](const llvm::ErrorInfoBase &EIB) { 348 if (EIB.convertToErrorCode() == 349 llvm::object::object_error::invalid_file_type) 350 // As a fallback, treat the buffer as a raw AST. 351 PCH = Buffer.getBuffer(); 352 else 353 EIB.log(llvm::errs()); 354 }); 355 return PCH; 356 } 357