1 //===- ASTWriter.cpp - AST File Writer ------------------------------------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // This file defines the ASTWriter class, which writes AST files. 10 // 11 //===----------------------------------------------------------------------===// 12 13 #include "ASTCommon.h" 14 #include "ASTReaderInternals.h" 15 #include "MultiOnDiskHashTable.h" 16 #include "clang/AST/ASTContext.h" 17 #include "clang/AST/ASTUnresolvedSet.h" 18 #include "clang/AST/AbstractTypeWriter.h" 19 #include "clang/AST/Attr.h" 20 #include "clang/AST/Decl.h" 21 #include "clang/AST/DeclBase.h" 22 #include "clang/AST/DeclCXX.h" 23 #include "clang/AST/DeclContextInternals.h" 24 #include "clang/AST/DeclFriend.h" 25 #include "clang/AST/DeclObjC.h" 26 #include "clang/AST/DeclTemplate.h" 27 #include "clang/AST/DeclarationName.h" 28 #include "clang/AST/Expr.h" 29 #include "clang/AST/ExprCXX.h" 30 #include "clang/AST/LambdaCapture.h" 31 #include "clang/AST/NestedNameSpecifier.h" 32 #include "clang/AST/OpenMPClause.h" 33 #include "clang/AST/RawCommentList.h" 34 #include "clang/AST/TemplateName.h" 35 #include "clang/AST/Type.h" 36 #include "clang/AST/TypeLocVisitor.h" 37 #include "clang/Basic/Diagnostic.h" 38 #include "clang/Basic/DiagnosticOptions.h" 39 #include "clang/Basic/FileManager.h" 40 #include "clang/Basic/FileSystemOptions.h" 41 #include "clang/Basic/IdentifierTable.h" 42 #include "clang/Basic/LLVM.h" 43 #include "clang/Basic/Lambda.h" 44 #include "clang/Basic/LangOptions.h" 45 #include "clang/Basic/Module.h" 46 #include "clang/Basic/ObjCRuntime.h" 47 #include "clang/Basic/OpenCLOptions.h" 48 #include "clang/Basic/SourceLocation.h" 49 #include "clang/Basic/SourceManager.h" 50 #include "clang/Basic/SourceManagerInternals.h" 51 #include "clang/Basic/Specifiers.h" 52 #include "clang/Basic/TargetInfo.h" 53 #include "clang/Basic/TargetOptions.h" 54 #include "clang/Basic/Version.h" 55 #include "clang/Lex/HeaderSearch.h" 56 #include "clang/Lex/HeaderSearchOptions.h" 57 #include "clang/Lex/MacroInfo.h" 58 #include "clang/Lex/ModuleMap.h" 59 #include "clang/Lex/PreprocessingRecord.h" 60 #include "clang/Lex/Preprocessor.h" 61 #include "clang/Lex/PreprocessorOptions.h" 62 #include "clang/Lex/Token.h" 63 #include "clang/Sema/IdentifierResolver.h" 64 #include "clang/Sema/ObjCMethodList.h" 65 #include "clang/Sema/Sema.h" 66 #include "clang/Sema/Weak.h" 67 #include "clang/Serialization/ASTBitCodes.h" 68 #include "clang/Serialization/ASTReader.h" 69 #include "clang/Serialization/ASTRecordWriter.h" 70 #include "clang/Serialization/InMemoryModuleCache.h" 71 #include "clang/Serialization/ModuleFile.h" 72 #include "clang/Serialization/ModuleFileExtension.h" 73 #include "clang/Serialization/SerializationDiagnostic.h" 74 #include "llvm/ADT/APFloat.h" 75 #include "llvm/ADT/APInt.h" 76 #include "llvm/ADT/APSInt.h" 77 #include "llvm/ADT/ArrayRef.h" 78 #include "llvm/ADT/DenseMap.h" 79 #include "llvm/ADT/Hashing.h" 80 #include "llvm/ADT/Optional.h" 81 #include "llvm/ADT/PointerIntPair.h" 82 #include "llvm/ADT/STLExtras.h" 83 #include "llvm/ADT/ScopeExit.h" 84 #include "llvm/ADT/SmallPtrSet.h" 85 #include "llvm/ADT/SmallString.h" 86 #include "llvm/ADT/SmallVector.h" 87 #include "llvm/ADT/StringMap.h" 88 #include "llvm/ADT/StringRef.h" 89 #include "llvm/Bitstream/BitCodes.h" 90 #include "llvm/Bitstream/BitstreamWriter.h" 91 #include "llvm/Support/Casting.h" 92 #include "llvm/Support/Compression.h" 93 #include "llvm/Support/DJB.h" 94 #include "llvm/Support/Endian.h" 95 #include "llvm/Support/EndianStream.h" 96 #include "llvm/Support/Error.h" 97 #include "llvm/Support/ErrorHandling.h" 98 #include "llvm/Support/LEB128.h" 99 #include "llvm/Support/MemoryBuffer.h" 100 #include "llvm/Support/OnDiskHashTable.h" 101 #include "llvm/Support/Path.h" 102 #include "llvm/Support/SHA1.h" 103 #include "llvm/Support/VersionTuple.h" 104 #include "llvm/Support/raw_ostream.h" 105 #include <algorithm> 106 #include <cassert> 107 #include <cstdint> 108 #include <cstdlib> 109 #include <cstring> 110 #include <ctime> 111 #include <deque> 112 #include <limits> 113 #include <memory> 114 #include <queue> 115 #include <tuple> 116 #include <utility> 117 #include <vector> 118 119 using namespace clang; 120 using namespace clang::serialization; 121 122 template <typename T, typename Allocator> 123 static StringRef bytes(const std::vector<T, Allocator> &v) { 124 if (v.empty()) return StringRef(); 125 return StringRef(reinterpret_cast<const char*>(&v[0]), 126 sizeof(T) * v.size()); 127 } 128 129 template <typename T> 130 static StringRef bytes(const SmallVectorImpl<T> &v) { 131 return StringRef(reinterpret_cast<const char*>(v.data()), 132 sizeof(T) * v.size()); 133 } 134 135 static std::string bytes(const std::vector<bool> &V) { 136 std::string Str; 137 Str.reserve(V.size() / 8); 138 for (unsigned I = 0, E = V.size(); I < E;) { 139 char Byte = 0; 140 for (unsigned Bit = 0; Bit < 8 && I < E; ++Bit, ++I) 141 Byte |= V[I] << Bit; 142 Str += Byte; 143 } 144 return Str; 145 } 146 147 //===----------------------------------------------------------------------===// 148 // Type serialization 149 //===----------------------------------------------------------------------===// 150 151 static TypeCode getTypeCodeForTypeClass(Type::TypeClass id) { 152 switch (id) { 153 #define TYPE_BIT_CODE(CLASS_ID, CODE_ID, CODE_VALUE) \ 154 case Type::CLASS_ID: return TYPE_##CODE_ID; 155 #include "clang/Serialization/TypeBitCodes.def" 156 case Type::Builtin: 157 llvm_unreachable("shouldn't be serializing a builtin type this way"); 158 } 159 llvm_unreachable("bad type kind"); 160 } 161 162 namespace { 163 164 std::set<const FileEntry *> GetAllModuleMaps(const HeaderSearch &HS, 165 Module *RootModule) { 166 std::set<const FileEntry *> ModuleMaps{}; 167 std::set<const Module *> ProcessedModules; 168 SmallVector<const Module *> ModulesToProcess{RootModule}; 169 170 SmallVector<const FileEntry *, 16> FilesByUID; 171 HS.getFileMgr().GetUniqueIDMapping(FilesByUID); 172 173 if (FilesByUID.size() > HS.header_file_size()) 174 FilesByUID.resize(HS.header_file_size()); 175 176 for (unsigned UID = 0, LastUID = FilesByUID.size(); UID != LastUID; ++UID) { 177 const FileEntry *File = FilesByUID[UID]; 178 if (!File) 179 continue; 180 181 const HeaderFileInfo *HFI = 182 HS.getExistingFileInfo(File, /*WantExternal*/ false); 183 if (!HFI || (HFI->isModuleHeader && !HFI->isCompilingModuleHeader)) 184 continue; 185 186 for (const auto &KH : HS.findAllModulesForHeader(File)) { 187 if (!KH.getModule()) 188 continue; 189 ModulesToProcess.push_back(KH.getModule()); 190 } 191 } 192 193 while (!ModulesToProcess.empty()) { 194 auto *CurrentModule = ModulesToProcess.pop_back_val(); 195 ProcessedModules.insert(CurrentModule); 196 197 auto *ModuleMapFile = 198 HS.getModuleMap().getModuleMapFileForUniquing(CurrentModule); 199 if (!ModuleMapFile) { 200 continue; 201 } 202 203 ModuleMaps.insert(ModuleMapFile); 204 205 for (auto *ImportedModule : (CurrentModule)->Imports) { 206 if (!ImportedModule || 207 ProcessedModules.find(ImportedModule) != ProcessedModules.end()) { 208 continue; 209 } 210 ModulesToProcess.push_back(ImportedModule); 211 } 212 213 for (const Module *UndeclaredModule : CurrentModule->UndeclaredUses) 214 if (UndeclaredModule && 215 ProcessedModules.find(UndeclaredModule) == ProcessedModules.end()) 216 ModulesToProcess.push_back(UndeclaredModule); 217 } 218 219 return ModuleMaps; 220 } 221 222 class ASTTypeWriter { 223 ASTWriter &Writer; 224 ASTWriter::RecordData Record; 225 ASTRecordWriter BasicWriter; 226 227 public: 228 ASTTypeWriter(ASTWriter &Writer) 229 : Writer(Writer), BasicWriter(Writer, Record) {} 230 231 uint64_t write(QualType T) { 232 if (T.hasLocalNonFastQualifiers()) { 233 Qualifiers Qs = T.getLocalQualifiers(); 234 BasicWriter.writeQualType(T.getLocalUnqualifiedType()); 235 BasicWriter.writeQualifiers(Qs); 236 return BasicWriter.Emit(TYPE_EXT_QUAL, Writer.getTypeExtQualAbbrev()); 237 } 238 239 const Type *typePtr = T.getTypePtr(); 240 serialization::AbstractTypeWriter<ASTRecordWriter> atw(BasicWriter); 241 atw.write(typePtr); 242 return BasicWriter.Emit(getTypeCodeForTypeClass(typePtr->getTypeClass()), 243 /*abbrev*/ 0); 244 } 245 }; 246 247 class TypeLocWriter : public TypeLocVisitor<TypeLocWriter> { 248 using LocSeq = SourceLocationSequence; 249 250 ASTRecordWriter &Record; 251 LocSeq *Seq; 252 253 void addSourceLocation(SourceLocation Loc) { 254 Record.AddSourceLocation(Loc, Seq); 255 } 256 void addSourceRange(SourceRange Range) { Record.AddSourceRange(Range, Seq); } 257 258 public: 259 TypeLocWriter(ASTRecordWriter &Record, LocSeq *Seq) 260 : Record(Record), Seq(Seq) {} 261 262 #define ABSTRACT_TYPELOC(CLASS, PARENT) 263 #define TYPELOC(CLASS, PARENT) \ 264 void Visit##CLASS##TypeLoc(CLASS##TypeLoc TyLoc); 265 #include "clang/AST/TypeLocNodes.def" 266 267 void VisitArrayTypeLoc(ArrayTypeLoc TyLoc); 268 void VisitFunctionTypeLoc(FunctionTypeLoc TyLoc); 269 }; 270 271 } // namespace 272 273 void TypeLocWriter::VisitQualifiedTypeLoc(QualifiedTypeLoc TL) { 274 // nothing to do 275 } 276 277 void TypeLocWriter::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) { 278 addSourceLocation(TL.getBuiltinLoc()); 279 if (TL.needsExtraLocalData()) { 280 Record.push_back(TL.getWrittenTypeSpec()); 281 Record.push_back(static_cast<uint64_t>(TL.getWrittenSignSpec())); 282 Record.push_back(static_cast<uint64_t>(TL.getWrittenWidthSpec())); 283 Record.push_back(TL.hasModeAttr()); 284 } 285 } 286 287 void TypeLocWriter::VisitComplexTypeLoc(ComplexTypeLoc TL) { 288 addSourceLocation(TL.getNameLoc()); 289 } 290 291 void TypeLocWriter::VisitPointerTypeLoc(PointerTypeLoc TL) { 292 addSourceLocation(TL.getStarLoc()); 293 } 294 295 void TypeLocWriter::VisitDecayedTypeLoc(DecayedTypeLoc TL) { 296 // nothing to do 297 } 298 299 void TypeLocWriter::VisitAdjustedTypeLoc(AdjustedTypeLoc TL) { 300 // nothing to do 301 } 302 303 void TypeLocWriter::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) { 304 addSourceLocation(TL.getCaretLoc()); 305 } 306 307 void TypeLocWriter::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) { 308 addSourceLocation(TL.getAmpLoc()); 309 } 310 311 void TypeLocWriter::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) { 312 addSourceLocation(TL.getAmpAmpLoc()); 313 } 314 315 void TypeLocWriter::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) { 316 addSourceLocation(TL.getStarLoc()); 317 Record.AddTypeSourceInfo(TL.getClassTInfo()); 318 } 319 320 void TypeLocWriter::VisitArrayTypeLoc(ArrayTypeLoc TL) { 321 addSourceLocation(TL.getLBracketLoc()); 322 addSourceLocation(TL.getRBracketLoc()); 323 Record.push_back(TL.getSizeExpr() ? 1 : 0); 324 if (TL.getSizeExpr()) 325 Record.AddStmt(TL.getSizeExpr()); 326 } 327 328 void TypeLocWriter::VisitConstantArrayTypeLoc(ConstantArrayTypeLoc TL) { 329 VisitArrayTypeLoc(TL); 330 } 331 332 void TypeLocWriter::VisitIncompleteArrayTypeLoc(IncompleteArrayTypeLoc TL) { 333 VisitArrayTypeLoc(TL); 334 } 335 336 void TypeLocWriter::VisitVariableArrayTypeLoc(VariableArrayTypeLoc TL) { 337 VisitArrayTypeLoc(TL); 338 } 339 340 void TypeLocWriter::VisitDependentSizedArrayTypeLoc( 341 DependentSizedArrayTypeLoc TL) { 342 VisitArrayTypeLoc(TL); 343 } 344 345 void TypeLocWriter::VisitDependentAddressSpaceTypeLoc( 346 DependentAddressSpaceTypeLoc TL) { 347 addSourceLocation(TL.getAttrNameLoc()); 348 SourceRange range = TL.getAttrOperandParensRange(); 349 addSourceLocation(range.getBegin()); 350 addSourceLocation(range.getEnd()); 351 Record.AddStmt(TL.getAttrExprOperand()); 352 } 353 354 void TypeLocWriter::VisitDependentSizedExtVectorTypeLoc( 355 DependentSizedExtVectorTypeLoc TL) { 356 addSourceLocation(TL.getNameLoc()); 357 } 358 359 void TypeLocWriter::VisitVectorTypeLoc(VectorTypeLoc TL) { 360 addSourceLocation(TL.getNameLoc()); 361 } 362 363 void TypeLocWriter::VisitDependentVectorTypeLoc( 364 DependentVectorTypeLoc TL) { 365 addSourceLocation(TL.getNameLoc()); 366 } 367 368 void TypeLocWriter::VisitExtVectorTypeLoc(ExtVectorTypeLoc TL) { 369 addSourceLocation(TL.getNameLoc()); 370 } 371 372 void TypeLocWriter::VisitConstantMatrixTypeLoc(ConstantMatrixTypeLoc TL) { 373 addSourceLocation(TL.getAttrNameLoc()); 374 SourceRange range = TL.getAttrOperandParensRange(); 375 addSourceLocation(range.getBegin()); 376 addSourceLocation(range.getEnd()); 377 Record.AddStmt(TL.getAttrRowOperand()); 378 Record.AddStmt(TL.getAttrColumnOperand()); 379 } 380 381 void TypeLocWriter::VisitDependentSizedMatrixTypeLoc( 382 DependentSizedMatrixTypeLoc TL) { 383 addSourceLocation(TL.getAttrNameLoc()); 384 SourceRange range = TL.getAttrOperandParensRange(); 385 addSourceLocation(range.getBegin()); 386 addSourceLocation(range.getEnd()); 387 Record.AddStmt(TL.getAttrRowOperand()); 388 Record.AddStmt(TL.getAttrColumnOperand()); 389 } 390 391 void TypeLocWriter::VisitFunctionTypeLoc(FunctionTypeLoc TL) { 392 addSourceLocation(TL.getLocalRangeBegin()); 393 addSourceLocation(TL.getLParenLoc()); 394 addSourceLocation(TL.getRParenLoc()); 395 addSourceRange(TL.getExceptionSpecRange()); 396 addSourceLocation(TL.getLocalRangeEnd()); 397 for (unsigned i = 0, e = TL.getNumParams(); i != e; ++i) 398 Record.AddDeclRef(TL.getParam(i)); 399 } 400 401 void TypeLocWriter::VisitFunctionProtoTypeLoc(FunctionProtoTypeLoc TL) { 402 VisitFunctionTypeLoc(TL); 403 } 404 405 void TypeLocWriter::VisitFunctionNoProtoTypeLoc(FunctionNoProtoTypeLoc TL) { 406 VisitFunctionTypeLoc(TL); 407 } 408 409 void TypeLocWriter::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) { 410 addSourceLocation(TL.getNameLoc()); 411 } 412 413 void TypeLocWriter::VisitUsingTypeLoc(UsingTypeLoc TL) { 414 addSourceLocation(TL.getNameLoc()); 415 } 416 417 void TypeLocWriter::VisitTypedefTypeLoc(TypedefTypeLoc TL) { 418 addSourceLocation(TL.getNameLoc()); 419 } 420 421 void TypeLocWriter::VisitObjCTypeParamTypeLoc(ObjCTypeParamTypeLoc TL) { 422 if (TL.getNumProtocols()) { 423 addSourceLocation(TL.getProtocolLAngleLoc()); 424 addSourceLocation(TL.getProtocolRAngleLoc()); 425 } 426 for (unsigned i = 0, e = TL.getNumProtocols(); i != e; ++i) 427 addSourceLocation(TL.getProtocolLoc(i)); 428 } 429 430 void TypeLocWriter::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) { 431 addSourceLocation(TL.getTypeofLoc()); 432 addSourceLocation(TL.getLParenLoc()); 433 addSourceLocation(TL.getRParenLoc()); 434 } 435 436 void TypeLocWriter::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) { 437 addSourceLocation(TL.getTypeofLoc()); 438 addSourceLocation(TL.getLParenLoc()); 439 addSourceLocation(TL.getRParenLoc()); 440 Record.AddTypeSourceInfo(TL.getUnderlyingTInfo()); 441 } 442 443 void TypeLocWriter::VisitDecltypeTypeLoc(DecltypeTypeLoc TL) { 444 addSourceLocation(TL.getDecltypeLoc()); 445 addSourceLocation(TL.getRParenLoc()); 446 } 447 448 void TypeLocWriter::VisitUnaryTransformTypeLoc(UnaryTransformTypeLoc TL) { 449 addSourceLocation(TL.getKWLoc()); 450 addSourceLocation(TL.getLParenLoc()); 451 addSourceLocation(TL.getRParenLoc()); 452 Record.AddTypeSourceInfo(TL.getUnderlyingTInfo()); 453 } 454 455 void TypeLocWriter::VisitAutoTypeLoc(AutoTypeLoc TL) { 456 addSourceLocation(TL.getNameLoc()); 457 Record.push_back(TL.isConstrained()); 458 if (TL.isConstrained()) { 459 Record.AddNestedNameSpecifierLoc(TL.getNestedNameSpecifierLoc()); 460 addSourceLocation(TL.getTemplateKWLoc()); 461 addSourceLocation(TL.getConceptNameLoc()); 462 Record.AddDeclRef(TL.getFoundDecl()); 463 addSourceLocation(TL.getLAngleLoc()); 464 addSourceLocation(TL.getRAngleLoc()); 465 for (unsigned I = 0; I < TL.getNumArgs(); ++I) 466 Record.AddTemplateArgumentLocInfo(TL.getTypePtr()->getArg(I).getKind(), 467 TL.getArgLocInfo(I)); 468 } 469 Record.push_back(TL.isDecltypeAuto()); 470 if (TL.isDecltypeAuto()) 471 addSourceLocation(TL.getRParenLoc()); 472 } 473 474 void TypeLocWriter::VisitDeducedTemplateSpecializationTypeLoc( 475 DeducedTemplateSpecializationTypeLoc TL) { 476 addSourceLocation(TL.getTemplateNameLoc()); 477 } 478 479 void TypeLocWriter::VisitRecordTypeLoc(RecordTypeLoc TL) { 480 addSourceLocation(TL.getNameLoc()); 481 } 482 483 void TypeLocWriter::VisitEnumTypeLoc(EnumTypeLoc TL) { 484 addSourceLocation(TL.getNameLoc()); 485 } 486 487 void TypeLocWriter::VisitAttributedTypeLoc(AttributedTypeLoc TL) { 488 Record.AddAttr(TL.getAttr()); 489 } 490 491 void TypeLocWriter::VisitBTFTagAttributedTypeLoc(BTFTagAttributedTypeLoc TL) { 492 // Nothing to do. 493 } 494 495 void TypeLocWriter::VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) { 496 addSourceLocation(TL.getNameLoc()); 497 } 498 499 void TypeLocWriter::VisitSubstTemplateTypeParmTypeLoc( 500 SubstTemplateTypeParmTypeLoc TL) { 501 addSourceLocation(TL.getNameLoc()); 502 } 503 504 void TypeLocWriter::VisitSubstTemplateTypeParmPackTypeLoc( 505 SubstTemplateTypeParmPackTypeLoc TL) { 506 addSourceLocation(TL.getNameLoc()); 507 } 508 509 void TypeLocWriter::VisitTemplateSpecializationTypeLoc( 510 TemplateSpecializationTypeLoc TL) { 511 addSourceLocation(TL.getTemplateKeywordLoc()); 512 addSourceLocation(TL.getTemplateNameLoc()); 513 addSourceLocation(TL.getLAngleLoc()); 514 addSourceLocation(TL.getRAngleLoc()); 515 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i) 516 Record.AddTemplateArgumentLocInfo(TL.getArgLoc(i).getArgument().getKind(), 517 TL.getArgLoc(i).getLocInfo()); 518 } 519 520 void TypeLocWriter::VisitParenTypeLoc(ParenTypeLoc TL) { 521 addSourceLocation(TL.getLParenLoc()); 522 addSourceLocation(TL.getRParenLoc()); 523 } 524 525 void TypeLocWriter::VisitMacroQualifiedTypeLoc(MacroQualifiedTypeLoc TL) { 526 addSourceLocation(TL.getExpansionLoc()); 527 } 528 529 void TypeLocWriter::VisitElaboratedTypeLoc(ElaboratedTypeLoc TL) { 530 addSourceLocation(TL.getElaboratedKeywordLoc()); 531 Record.AddNestedNameSpecifierLoc(TL.getQualifierLoc()); 532 } 533 534 void TypeLocWriter::VisitInjectedClassNameTypeLoc(InjectedClassNameTypeLoc TL) { 535 addSourceLocation(TL.getNameLoc()); 536 } 537 538 void TypeLocWriter::VisitDependentNameTypeLoc(DependentNameTypeLoc TL) { 539 addSourceLocation(TL.getElaboratedKeywordLoc()); 540 Record.AddNestedNameSpecifierLoc(TL.getQualifierLoc()); 541 addSourceLocation(TL.getNameLoc()); 542 } 543 544 void TypeLocWriter::VisitDependentTemplateSpecializationTypeLoc( 545 DependentTemplateSpecializationTypeLoc TL) { 546 addSourceLocation(TL.getElaboratedKeywordLoc()); 547 Record.AddNestedNameSpecifierLoc(TL.getQualifierLoc()); 548 addSourceLocation(TL.getTemplateKeywordLoc()); 549 addSourceLocation(TL.getTemplateNameLoc()); 550 addSourceLocation(TL.getLAngleLoc()); 551 addSourceLocation(TL.getRAngleLoc()); 552 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) 553 Record.AddTemplateArgumentLocInfo(TL.getArgLoc(I).getArgument().getKind(), 554 TL.getArgLoc(I).getLocInfo()); 555 } 556 557 void TypeLocWriter::VisitPackExpansionTypeLoc(PackExpansionTypeLoc TL) { 558 addSourceLocation(TL.getEllipsisLoc()); 559 } 560 561 void TypeLocWriter::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) { 562 addSourceLocation(TL.getNameLoc()); 563 } 564 565 void TypeLocWriter::VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) { 566 Record.push_back(TL.hasBaseTypeAsWritten()); 567 addSourceLocation(TL.getTypeArgsLAngleLoc()); 568 addSourceLocation(TL.getTypeArgsRAngleLoc()); 569 for (unsigned i = 0, e = TL.getNumTypeArgs(); i != e; ++i) 570 Record.AddTypeSourceInfo(TL.getTypeArgTInfo(i)); 571 addSourceLocation(TL.getProtocolLAngleLoc()); 572 addSourceLocation(TL.getProtocolRAngleLoc()); 573 for (unsigned i = 0, e = TL.getNumProtocols(); i != e; ++i) 574 addSourceLocation(TL.getProtocolLoc(i)); 575 } 576 577 void TypeLocWriter::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) { 578 addSourceLocation(TL.getStarLoc()); 579 } 580 581 void TypeLocWriter::VisitAtomicTypeLoc(AtomicTypeLoc TL) { 582 addSourceLocation(TL.getKWLoc()); 583 addSourceLocation(TL.getLParenLoc()); 584 addSourceLocation(TL.getRParenLoc()); 585 } 586 587 void TypeLocWriter::VisitPipeTypeLoc(PipeTypeLoc TL) { 588 addSourceLocation(TL.getKWLoc()); 589 } 590 591 void TypeLocWriter::VisitBitIntTypeLoc(clang::BitIntTypeLoc TL) { 592 addSourceLocation(TL.getNameLoc()); 593 } 594 void TypeLocWriter::VisitDependentBitIntTypeLoc( 595 clang::DependentBitIntTypeLoc TL) { 596 addSourceLocation(TL.getNameLoc()); 597 } 598 599 void ASTWriter::WriteTypeAbbrevs() { 600 using namespace llvm; 601 602 std::shared_ptr<BitCodeAbbrev> Abv; 603 604 // Abbreviation for TYPE_EXT_QUAL 605 Abv = std::make_shared<BitCodeAbbrev>(); 606 Abv->Add(BitCodeAbbrevOp(serialization::TYPE_EXT_QUAL)); 607 Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Type 608 Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 3)); // Quals 609 TypeExtQualAbbrev = Stream.EmitAbbrev(std::move(Abv)); 610 } 611 612 //===----------------------------------------------------------------------===// 613 // ASTWriter Implementation 614 //===----------------------------------------------------------------------===// 615 616 static void EmitBlockID(unsigned ID, const char *Name, 617 llvm::BitstreamWriter &Stream, 618 ASTWriter::RecordDataImpl &Record) { 619 Record.clear(); 620 Record.push_back(ID); 621 Stream.EmitRecord(llvm::bitc::BLOCKINFO_CODE_SETBID, Record); 622 623 // Emit the block name if present. 624 if (!Name || Name[0] == 0) 625 return; 626 Record.clear(); 627 while (*Name) 628 Record.push_back(*Name++); 629 Stream.EmitRecord(llvm::bitc::BLOCKINFO_CODE_BLOCKNAME, Record); 630 } 631 632 static void EmitRecordID(unsigned ID, const char *Name, 633 llvm::BitstreamWriter &Stream, 634 ASTWriter::RecordDataImpl &Record) { 635 Record.clear(); 636 Record.push_back(ID); 637 while (*Name) 638 Record.push_back(*Name++); 639 Stream.EmitRecord(llvm::bitc::BLOCKINFO_CODE_SETRECORDNAME, Record); 640 } 641 642 static void AddStmtsExprs(llvm::BitstreamWriter &Stream, 643 ASTWriter::RecordDataImpl &Record) { 644 #define RECORD(X) EmitRecordID(X, #X, Stream, Record) 645 RECORD(STMT_STOP); 646 RECORD(STMT_NULL_PTR); 647 RECORD(STMT_REF_PTR); 648 RECORD(STMT_NULL); 649 RECORD(STMT_COMPOUND); 650 RECORD(STMT_CASE); 651 RECORD(STMT_DEFAULT); 652 RECORD(STMT_LABEL); 653 RECORD(STMT_ATTRIBUTED); 654 RECORD(STMT_IF); 655 RECORD(STMT_SWITCH); 656 RECORD(STMT_WHILE); 657 RECORD(STMT_DO); 658 RECORD(STMT_FOR); 659 RECORD(STMT_GOTO); 660 RECORD(STMT_INDIRECT_GOTO); 661 RECORD(STMT_CONTINUE); 662 RECORD(STMT_BREAK); 663 RECORD(STMT_RETURN); 664 RECORD(STMT_DECL); 665 RECORD(STMT_GCCASM); 666 RECORD(STMT_MSASM); 667 RECORD(EXPR_PREDEFINED); 668 RECORD(EXPR_DECL_REF); 669 RECORD(EXPR_INTEGER_LITERAL); 670 RECORD(EXPR_FIXEDPOINT_LITERAL); 671 RECORD(EXPR_FLOATING_LITERAL); 672 RECORD(EXPR_IMAGINARY_LITERAL); 673 RECORD(EXPR_STRING_LITERAL); 674 RECORD(EXPR_CHARACTER_LITERAL); 675 RECORD(EXPR_PAREN); 676 RECORD(EXPR_PAREN_LIST); 677 RECORD(EXPR_UNARY_OPERATOR); 678 RECORD(EXPR_SIZEOF_ALIGN_OF); 679 RECORD(EXPR_ARRAY_SUBSCRIPT); 680 RECORD(EXPR_CALL); 681 RECORD(EXPR_MEMBER); 682 RECORD(EXPR_BINARY_OPERATOR); 683 RECORD(EXPR_COMPOUND_ASSIGN_OPERATOR); 684 RECORD(EXPR_CONDITIONAL_OPERATOR); 685 RECORD(EXPR_IMPLICIT_CAST); 686 RECORD(EXPR_CSTYLE_CAST); 687 RECORD(EXPR_COMPOUND_LITERAL); 688 RECORD(EXPR_EXT_VECTOR_ELEMENT); 689 RECORD(EXPR_INIT_LIST); 690 RECORD(EXPR_DESIGNATED_INIT); 691 RECORD(EXPR_DESIGNATED_INIT_UPDATE); 692 RECORD(EXPR_IMPLICIT_VALUE_INIT); 693 RECORD(EXPR_NO_INIT); 694 RECORD(EXPR_VA_ARG); 695 RECORD(EXPR_ADDR_LABEL); 696 RECORD(EXPR_STMT); 697 RECORD(EXPR_CHOOSE); 698 RECORD(EXPR_GNU_NULL); 699 RECORD(EXPR_SHUFFLE_VECTOR); 700 RECORD(EXPR_BLOCK); 701 RECORD(EXPR_GENERIC_SELECTION); 702 RECORD(EXPR_OBJC_STRING_LITERAL); 703 RECORD(EXPR_OBJC_BOXED_EXPRESSION); 704 RECORD(EXPR_OBJC_ARRAY_LITERAL); 705 RECORD(EXPR_OBJC_DICTIONARY_LITERAL); 706 RECORD(EXPR_OBJC_ENCODE); 707 RECORD(EXPR_OBJC_SELECTOR_EXPR); 708 RECORD(EXPR_OBJC_PROTOCOL_EXPR); 709 RECORD(EXPR_OBJC_IVAR_REF_EXPR); 710 RECORD(EXPR_OBJC_PROPERTY_REF_EXPR); 711 RECORD(EXPR_OBJC_KVC_REF_EXPR); 712 RECORD(EXPR_OBJC_MESSAGE_EXPR); 713 RECORD(STMT_OBJC_FOR_COLLECTION); 714 RECORD(STMT_OBJC_CATCH); 715 RECORD(STMT_OBJC_FINALLY); 716 RECORD(STMT_OBJC_AT_TRY); 717 RECORD(STMT_OBJC_AT_SYNCHRONIZED); 718 RECORD(STMT_OBJC_AT_THROW); 719 RECORD(EXPR_OBJC_BOOL_LITERAL); 720 RECORD(STMT_CXX_CATCH); 721 RECORD(STMT_CXX_TRY); 722 RECORD(STMT_CXX_FOR_RANGE); 723 RECORD(EXPR_CXX_OPERATOR_CALL); 724 RECORD(EXPR_CXX_MEMBER_CALL); 725 RECORD(EXPR_CXX_REWRITTEN_BINARY_OPERATOR); 726 RECORD(EXPR_CXX_CONSTRUCT); 727 RECORD(EXPR_CXX_TEMPORARY_OBJECT); 728 RECORD(EXPR_CXX_STATIC_CAST); 729 RECORD(EXPR_CXX_DYNAMIC_CAST); 730 RECORD(EXPR_CXX_REINTERPRET_CAST); 731 RECORD(EXPR_CXX_CONST_CAST); 732 RECORD(EXPR_CXX_ADDRSPACE_CAST); 733 RECORD(EXPR_CXX_FUNCTIONAL_CAST); 734 RECORD(EXPR_USER_DEFINED_LITERAL); 735 RECORD(EXPR_CXX_STD_INITIALIZER_LIST); 736 RECORD(EXPR_CXX_BOOL_LITERAL); 737 RECORD(EXPR_CXX_NULL_PTR_LITERAL); 738 RECORD(EXPR_CXX_TYPEID_EXPR); 739 RECORD(EXPR_CXX_TYPEID_TYPE); 740 RECORD(EXPR_CXX_THIS); 741 RECORD(EXPR_CXX_THROW); 742 RECORD(EXPR_CXX_DEFAULT_ARG); 743 RECORD(EXPR_CXX_DEFAULT_INIT); 744 RECORD(EXPR_CXX_BIND_TEMPORARY); 745 RECORD(EXPR_CXX_SCALAR_VALUE_INIT); 746 RECORD(EXPR_CXX_NEW); 747 RECORD(EXPR_CXX_DELETE); 748 RECORD(EXPR_CXX_PSEUDO_DESTRUCTOR); 749 RECORD(EXPR_EXPR_WITH_CLEANUPS); 750 RECORD(EXPR_CXX_DEPENDENT_SCOPE_MEMBER); 751 RECORD(EXPR_CXX_DEPENDENT_SCOPE_DECL_REF); 752 RECORD(EXPR_CXX_UNRESOLVED_CONSTRUCT); 753 RECORD(EXPR_CXX_UNRESOLVED_MEMBER); 754 RECORD(EXPR_CXX_UNRESOLVED_LOOKUP); 755 RECORD(EXPR_CXX_EXPRESSION_TRAIT); 756 RECORD(EXPR_CXX_NOEXCEPT); 757 RECORD(EXPR_OPAQUE_VALUE); 758 RECORD(EXPR_BINARY_CONDITIONAL_OPERATOR); 759 RECORD(EXPR_TYPE_TRAIT); 760 RECORD(EXPR_ARRAY_TYPE_TRAIT); 761 RECORD(EXPR_PACK_EXPANSION); 762 RECORD(EXPR_SIZEOF_PACK); 763 RECORD(EXPR_SUBST_NON_TYPE_TEMPLATE_PARM); 764 RECORD(EXPR_SUBST_NON_TYPE_TEMPLATE_PARM_PACK); 765 RECORD(EXPR_FUNCTION_PARM_PACK); 766 RECORD(EXPR_MATERIALIZE_TEMPORARY); 767 RECORD(EXPR_CUDA_KERNEL_CALL); 768 RECORD(EXPR_CXX_UUIDOF_EXPR); 769 RECORD(EXPR_CXX_UUIDOF_TYPE); 770 RECORD(EXPR_LAMBDA); 771 #undef RECORD 772 } 773 774 void ASTWriter::WriteBlockInfoBlock() { 775 RecordData Record; 776 Stream.EnterBlockInfoBlock(); 777 778 #define BLOCK(X) EmitBlockID(X ## _ID, #X, Stream, Record) 779 #define RECORD(X) EmitRecordID(X, #X, Stream, Record) 780 781 // Control Block. 782 BLOCK(CONTROL_BLOCK); 783 RECORD(METADATA); 784 RECORD(MODULE_NAME); 785 RECORD(MODULE_DIRECTORY); 786 RECORD(MODULE_MAP_FILE); 787 RECORD(IMPORTS); 788 RECORD(ORIGINAL_FILE); 789 RECORD(ORIGINAL_PCH_DIR); 790 RECORD(ORIGINAL_FILE_ID); 791 RECORD(INPUT_FILE_OFFSETS); 792 793 BLOCK(OPTIONS_BLOCK); 794 RECORD(LANGUAGE_OPTIONS); 795 RECORD(TARGET_OPTIONS); 796 RECORD(FILE_SYSTEM_OPTIONS); 797 RECORD(HEADER_SEARCH_OPTIONS); 798 RECORD(PREPROCESSOR_OPTIONS); 799 800 BLOCK(INPUT_FILES_BLOCK); 801 RECORD(INPUT_FILE); 802 RECORD(INPUT_FILE_HASH); 803 804 // AST Top-Level Block. 805 BLOCK(AST_BLOCK); 806 RECORD(TYPE_OFFSET); 807 RECORD(DECL_OFFSET); 808 RECORD(IDENTIFIER_OFFSET); 809 RECORD(IDENTIFIER_TABLE); 810 RECORD(EAGERLY_DESERIALIZED_DECLS); 811 RECORD(MODULAR_CODEGEN_DECLS); 812 RECORD(SPECIAL_TYPES); 813 RECORD(STATISTICS); 814 RECORD(TENTATIVE_DEFINITIONS); 815 RECORD(SELECTOR_OFFSETS); 816 RECORD(METHOD_POOL); 817 RECORD(PP_COUNTER_VALUE); 818 RECORD(SOURCE_LOCATION_OFFSETS); 819 RECORD(SOURCE_LOCATION_PRELOADS); 820 RECORD(EXT_VECTOR_DECLS); 821 RECORD(UNUSED_FILESCOPED_DECLS); 822 RECORD(PPD_ENTITIES_OFFSETS); 823 RECORD(VTABLE_USES); 824 RECORD(PPD_SKIPPED_RANGES); 825 RECORD(REFERENCED_SELECTOR_POOL); 826 RECORD(TU_UPDATE_LEXICAL); 827 RECORD(SEMA_DECL_REFS); 828 RECORD(WEAK_UNDECLARED_IDENTIFIERS); 829 RECORD(PENDING_IMPLICIT_INSTANTIATIONS); 830 RECORD(UPDATE_VISIBLE); 831 RECORD(DECL_UPDATE_OFFSETS); 832 RECORD(DECL_UPDATES); 833 RECORD(CUDA_SPECIAL_DECL_REFS); 834 RECORD(HEADER_SEARCH_TABLE); 835 RECORD(FP_PRAGMA_OPTIONS); 836 RECORD(OPENCL_EXTENSIONS); 837 RECORD(OPENCL_EXTENSION_TYPES); 838 RECORD(OPENCL_EXTENSION_DECLS); 839 RECORD(DELEGATING_CTORS); 840 RECORD(KNOWN_NAMESPACES); 841 RECORD(MODULE_OFFSET_MAP); 842 RECORD(SOURCE_MANAGER_LINE_TABLE); 843 RECORD(OBJC_CATEGORIES_MAP); 844 RECORD(FILE_SORTED_DECLS); 845 RECORD(IMPORTED_MODULES); 846 RECORD(OBJC_CATEGORIES); 847 RECORD(MACRO_OFFSET); 848 RECORD(INTERESTING_IDENTIFIERS); 849 RECORD(UNDEFINED_BUT_USED); 850 RECORD(LATE_PARSED_TEMPLATE); 851 RECORD(OPTIMIZE_PRAGMA_OPTIONS); 852 RECORD(MSSTRUCT_PRAGMA_OPTIONS); 853 RECORD(POINTERS_TO_MEMBERS_PRAGMA_OPTIONS); 854 RECORD(UNUSED_LOCAL_TYPEDEF_NAME_CANDIDATES); 855 RECORD(DELETE_EXPRS_TO_ANALYZE); 856 RECORD(CUDA_PRAGMA_FORCE_HOST_DEVICE_DEPTH); 857 RECORD(PP_CONDITIONAL_STACK); 858 RECORD(DECLS_TO_CHECK_FOR_DEFERRED_DIAGS); 859 RECORD(PP_INCLUDED_FILES); 860 RECORD(PP_ASSUME_NONNULL_LOC); 861 862 // SourceManager Block. 863 BLOCK(SOURCE_MANAGER_BLOCK); 864 RECORD(SM_SLOC_FILE_ENTRY); 865 RECORD(SM_SLOC_BUFFER_ENTRY); 866 RECORD(SM_SLOC_BUFFER_BLOB); 867 RECORD(SM_SLOC_BUFFER_BLOB_COMPRESSED); 868 RECORD(SM_SLOC_EXPANSION_ENTRY); 869 870 // Preprocessor Block. 871 BLOCK(PREPROCESSOR_BLOCK); 872 RECORD(PP_MACRO_DIRECTIVE_HISTORY); 873 RECORD(PP_MACRO_FUNCTION_LIKE); 874 RECORD(PP_MACRO_OBJECT_LIKE); 875 RECORD(PP_MODULE_MACRO); 876 RECORD(PP_TOKEN); 877 878 // Submodule Block. 879 BLOCK(SUBMODULE_BLOCK); 880 RECORD(SUBMODULE_METADATA); 881 RECORD(SUBMODULE_DEFINITION); 882 RECORD(SUBMODULE_UMBRELLA_HEADER); 883 RECORD(SUBMODULE_HEADER); 884 RECORD(SUBMODULE_TOPHEADER); 885 RECORD(SUBMODULE_UMBRELLA_DIR); 886 RECORD(SUBMODULE_IMPORTS); 887 RECORD(SUBMODULE_EXPORTS); 888 RECORD(SUBMODULE_REQUIRES); 889 RECORD(SUBMODULE_EXCLUDED_HEADER); 890 RECORD(SUBMODULE_LINK_LIBRARY); 891 RECORD(SUBMODULE_CONFIG_MACRO); 892 RECORD(SUBMODULE_CONFLICT); 893 RECORD(SUBMODULE_PRIVATE_HEADER); 894 RECORD(SUBMODULE_TEXTUAL_HEADER); 895 RECORD(SUBMODULE_PRIVATE_TEXTUAL_HEADER); 896 RECORD(SUBMODULE_INITIALIZERS); 897 RECORD(SUBMODULE_EXPORT_AS); 898 899 // Comments Block. 900 BLOCK(COMMENTS_BLOCK); 901 RECORD(COMMENTS_RAW_COMMENT); 902 903 // Decls and Types block. 904 BLOCK(DECLTYPES_BLOCK); 905 RECORD(TYPE_EXT_QUAL); 906 RECORD(TYPE_COMPLEX); 907 RECORD(TYPE_POINTER); 908 RECORD(TYPE_BLOCK_POINTER); 909 RECORD(TYPE_LVALUE_REFERENCE); 910 RECORD(TYPE_RVALUE_REFERENCE); 911 RECORD(TYPE_MEMBER_POINTER); 912 RECORD(TYPE_CONSTANT_ARRAY); 913 RECORD(TYPE_INCOMPLETE_ARRAY); 914 RECORD(TYPE_VARIABLE_ARRAY); 915 RECORD(TYPE_VECTOR); 916 RECORD(TYPE_EXT_VECTOR); 917 RECORD(TYPE_FUNCTION_NO_PROTO); 918 RECORD(TYPE_FUNCTION_PROTO); 919 RECORD(TYPE_TYPEDEF); 920 RECORD(TYPE_TYPEOF_EXPR); 921 RECORD(TYPE_TYPEOF); 922 RECORD(TYPE_RECORD); 923 RECORD(TYPE_ENUM); 924 RECORD(TYPE_OBJC_INTERFACE); 925 RECORD(TYPE_OBJC_OBJECT_POINTER); 926 RECORD(TYPE_DECLTYPE); 927 RECORD(TYPE_ELABORATED); 928 RECORD(TYPE_SUBST_TEMPLATE_TYPE_PARM); 929 RECORD(TYPE_UNRESOLVED_USING); 930 RECORD(TYPE_INJECTED_CLASS_NAME); 931 RECORD(TYPE_OBJC_OBJECT); 932 RECORD(TYPE_TEMPLATE_TYPE_PARM); 933 RECORD(TYPE_TEMPLATE_SPECIALIZATION); 934 RECORD(TYPE_DEPENDENT_NAME); 935 RECORD(TYPE_DEPENDENT_TEMPLATE_SPECIALIZATION); 936 RECORD(TYPE_DEPENDENT_SIZED_ARRAY); 937 RECORD(TYPE_PAREN); 938 RECORD(TYPE_MACRO_QUALIFIED); 939 RECORD(TYPE_PACK_EXPANSION); 940 RECORD(TYPE_ATTRIBUTED); 941 RECORD(TYPE_SUBST_TEMPLATE_TYPE_PARM_PACK); 942 RECORD(TYPE_AUTO); 943 RECORD(TYPE_UNARY_TRANSFORM); 944 RECORD(TYPE_ATOMIC); 945 RECORD(TYPE_DECAYED); 946 RECORD(TYPE_ADJUSTED); 947 RECORD(TYPE_OBJC_TYPE_PARAM); 948 RECORD(LOCAL_REDECLARATIONS); 949 RECORD(DECL_TYPEDEF); 950 RECORD(DECL_TYPEALIAS); 951 RECORD(DECL_ENUM); 952 RECORD(DECL_RECORD); 953 RECORD(DECL_ENUM_CONSTANT); 954 RECORD(DECL_FUNCTION); 955 RECORD(DECL_OBJC_METHOD); 956 RECORD(DECL_OBJC_INTERFACE); 957 RECORD(DECL_OBJC_PROTOCOL); 958 RECORD(DECL_OBJC_IVAR); 959 RECORD(DECL_OBJC_AT_DEFS_FIELD); 960 RECORD(DECL_OBJC_CATEGORY); 961 RECORD(DECL_OBJC_CATEGORY_IMPL); 962 RECORD(DECL_OBJC_IMPLEMENTATION); 963 RECORD(DECL_OBJC_COMPATIBLE_ALIAS); 964 RECORD(DECL_OBJC_PROPERTY); 965 RECORD(DECL_OBJC_PROPERTY_IMPL); 966 RECORD(DECL_FIELD); 967 RECORD(DECL_MS_PROPERTY); 968 RECORD(DECL_VAR); 969 RECORD(DECL_IMPLICIT_PARAM); 970 RECORD(DECL_PARM_VAR); 971 RECORD(DECL_FILE_SCOPE_ASM); 972 RECORD(DECL_BLOCK); 973 RECORD(DECL_CONTEXT_LEXICAL); 974 RECORD(DECL_CONTEXT_VISIBLE); 975 RECORD(DECL_NAMESPACE); 976 RECORD(DECL_NAMESPACE_ALIAS); 977 RECORD(DECL_USING); 978 RECORD(DECL_USING_SHADOW); 979 RECORD(DECL_USING_DIRECTIVE); 980 RECORD(DECL_UNRESOLVED_USING_VALUE); 981 RECORD(DECL_UNRESOLVED_USING_TYPENAME); 982 RECORD(DECL_LINKAGE_SPEC); 983 RECORD(DECL_CXX_RECORD); 984 RECORD(DECL_CXX_METHOD); 985 RECORD(DECL_CXX_CONSTRUCTOR); 986 RECORD(DECL_CXX_DESTRUCTOR); 987 RECORD(DECL_CXX_CONVERSION); 988 RECORD(DECL_ACCESS_SPEC); 989 RECORD(DECL_FRIEND); 990 RECORD(DECL_FRIEND_TEMPLATE); 991 RECORD(DECL_CLASS_TEMPLATE); 992 RECORD(DECL_CLASS_TEMPLATE_SPECIALIZATION); 993 RECORD(DECL_CLASS_TEMPLATE_PARTIAL_SPECIALIZATION); 994 RECORD(DECL_VAR_TEMPLATE); 995 RECORD(DECL_VAR_TEMPLATE_SPECIALIZATION); 996 RECORD(DECL_VAR_TEMPLATE_PARTIAL_SPECIALIZATION); 997 RECORD(DECL_FUNCTION_TEMPLATE); 998 RECORD(DECL_TEMPLATE_TYPE_PARM); 999 RECORD(DECL_NON_TYPE_TEMPLATE_PARM); 1000 RECORD(DECL_TEMPLATE_TEMPLATE_PARM); 1001 RECORD(DECL_CONCEPT); 1002 RECORD(DECL_REQUIRES_EXPR_BODY); 1003 RECORD(DECL_TYPE_ALIAS_TEMPLATE); 1004 RECORD(DECL_STATIC_ASSERT); 1005 RECORD(DECL_CXX_BASE_SPECIFIERS); 1006 RECORD(DECL_CXX_CTOR_INITIALIZERS); 1007 RECORD(DECL_INDIRECTFIELD); 1008 RECORD(DECL_EXPANDED_NON_TYPE_TEMPLATE_PARM_PACK); 1009 RECORD(DECL_EXPANDED_TEMPLATE_TEMPLATE_PARM_PACK); 1010 RECORD(DECL_CLASS_SCOPE_FUNCTION_SPECIALIZATION); 1011 RECORD(DECL_IMPORT); 1012 RECORD(DECL_OMP_THREADPRIVATE); 1013 RECORD(DECL_EMPTY); 1014 RECORD(DECL_OBJC_TYPE_PARAM); 1015 RECORD(DECL_OMP_CAPTUREDEXPR); 1016 RECORD(DECL_PRAGMA_COMMENT); 1017 RECORD(DECL_PRAGMA_DETECT_MISMATCH); 1018 RECORD(DECL_OMP_DECLARE_REDUCTION); 1019 RECORD(DECL_OMP_ALLOCATE); 1020 1021 // Statements and Exprs can occur in the Decls and Types block. 1022 AddStmtsExprs(Stream, Record); 1023 1024 BLOCK(PREPROCESSOR_DETAIL_BLOCK); 1025 RECORD(PPD_MACRO_EXPANSION); 1026 RECORD(PPD_MACRO_DEFINITION); 1027 RECORD(PPD_INCLUSION_DIRECTIVE); 1028 1029 // Decls and Types block. 1030 BLOCK(EXTENSION_BLOCK); 1031 RECORD(EXTENSION_METADATA); 1032 1033 BLOCK(UNHASHED_CONTROL_BLOCK); 1034 RECORD(SIGNATURE); 1035 RECORD(AST_BLOCK_HASH); 1036 RECORD(DIAGNOSTIC_OPTIONS); 1037 RECORD(DIAG_PRAGMA_MAPPINGS); 1038 1039 #undef RECORD 1040 #undef BLOCK 1041 Stream.ExitBlock(); 1042 } 1043 1044 /// Prepares a path for being written to an AST file by converting it 1045 /// to an absolute path and removing nested './'s. 1046 /// 1047 /// \return \c true if the path was changed. 1048 static bool cleanPathForOutput(FileManager &FileMgr, 1049 SmallVectorImpl<char> &Path) { 1050 bool Changed = FileMgr.makeAbsolutePath(Path); 1051 return Changed | llvm::sys::path::remove_dots(Path); 1052 } 1053 1054 /// Adjusts the given filename to only write out the portion of the 1055 /// filename that is not part of the system root directory. 1056 /// 1057 /// \param Filename the file name to adjust. 1058 /// 1059 /// \param BaseDir When non-NULL, the PCH file is a relocatable AST file and 1060 /// the returned filename will be adjusted by this root directory. 1061 /// 1062 /// \returns either the original filename (if it needs no adjustment) or the 1063 /// adjusted filename (which points into the @p Filename parameter). 1064 static const char * 1065 adjustFilenameForRelocatableAST(const char *Filename, StringRef BaseDir) { 1066 assert(Filename && "No file name to adjust?"); 1067 1068 if (BaseDir.empty()) 1069 return Filename; 1070 1071 // Verify that the filename and the system root have the same prefix. 1072 unsigned Pos = 0; 1073 for (; Filename[Pos] && Pos < BaseDir.size(); ++Pos) 1074 if (Filename[Pos] != BaseDir[Pos]) 1075 return Filename; // Prefixes don't match. 1076 1077 // We hit the end of the filename before we hit the end of the system root. 1078 if (!Filename[Pos]) 1079 return Filename; 1080 1081 // If there's not a path separator at the end of the base directory nor 1082 // immediately after it, then this isn't within the base directory. 1083 if (!llvm::sys::path::is_separator(Filename[Pos])) { 1084 if (!llvm::sys::path::is_separator(BaseDir.back())) 1085 return Filename; 1086 } else { 1087 // If the file name has a '/' at the current position, skip over the '/'. 1088 // We distinguish relative paths from absolute paths by the 1089 // absence of '/' at the beginning of relative paths. 1090 // 1091 // FIXME: This is wrong. We distinguish them by asking if the path is 1092 // absolute, which isn't the same thing. And there might be multiple '/'s 1093 // in a row. Use a better mechanism to indicate whether we have emitted an 1094 // absolute or relative path. 1095 ++Pos; 1096 } 1097 1098 return Filename + Pos; 1099 } 1100 1101 std::pair<ASTFileSignature, ASTFileSignature> 1102 ASTWriter::createSignature(StringRef AllBytes, StringRef ASTBlockBytes) { 1103 llvm::SHA1 Hasher; 1104 Hasher.update(ASTBlockBytes); 1105 ASTFileSignature ASTBlockHash = ASTFileSignature::create(Hasher.result()); 1106 1107 // Add the remaining bytes (i.e. bytes before the unhashed control block that 1108 // are not part of the AST block). 1109 Hasher.update( 1110 AllBytes.take_front(ASTBlockBytes.bytes_end() - AllBytes.bytes_begin())); 1111 Hasher.update( 1112 AllBytes.take_back(AllBytes.bytes_end() - ASTBlockBytes.bytes_end())); 1113 ASTFileSignature Signature = ASTFileSignature::create(Hasher.result()); 1114 1115 return std::make_pair(ASTBlockHash, Signature); 1116 } 1117 1118 ASTFileSignature ASTWriter::writeUnhashedControlBlock(Preprocessor &PP, 1119 ASTContext &Context) { 1120 using namespace llvm; 1121 1122 // Flush first to prepare the PCM hash (signature). 1123 Stream.FlushToWord(); 1124 auto StartOfUnhashedControl = Stream.GetCurrentBitNo() >> 3; 1125 1126 // Enter the block and prepare to write records. 1127 RecordData Record; 1128 Stream.EnterSubblock(UNHASHED_CONTROL_BLOCK_ID, 5); 1129 1130 // For implicit modules, write the hash of the PCM as its signature. 1131 ASTFileSignature Signature; 1132 if (WritingModule && 1133 PP.getHeaderSearchInfo().getHeaderSearchOpts().ModulesHashContent) { 1134 ASTFileSignature ASTBlockHash; 1135 auto ASTBlockStartByte = ASTBlockRange.first >> 3; 1136 auto ASTBlockByteLength = (ASTBlockRange.second >> 3) - ASTBlockStartByte; 1137 std::tie(ASTBlockHash, Signature) = createSignature( 1138 StringRef(Buffer.begin(), StartOfUnhashedControl), 1139 StringRef(Buffer.begin() + ASTBlockStartByte, ASTBlockByteLength)); 1140 1141 Record.append(ASTBlockHash.begin(), ASTBlockHash.end()); 1142 Stream.EmitRecord(AST_BLOCK_HASH, Record); 1143 Record.clear(); 1144 Record.append(Signature.begin(), Signature.end()); 1145 Stream.EmitRecord(SIGNATURE, Record); 1146 Record.clear(); 1147 } 1148 1149 // Diagnostic options. 1150 const auto &Diags = Context.getDiagnostics(); 1151 const DiagnosticOptions &DiagOpts = Diags.getDiagnosticOptions(); 1152 #define DIAGOPT(Name, Bits, Default) Record.push_back(DiagOpts.Name); 1153 #define ENUM_DIAGOPT(Name, Type, Bits, Default) \ 1154 Record.push_back(static_cast<unsigned>(DiagOpts.get##Name())); 1155 #include "clang/Basic/DiagnosticOptions.def" 1156 Record.push_back(DiagOpts.Warnings.size()); 1157 for (unsigned I = 0, N = DiagOpts.Warnings.size(); I != N; ++I) 1158 AddString(DiagOpts.Warnings[I], Record); 1159 Record.push_back(DiagOpts.Remarks.size()); 1160 for (unsigned I = 0, N = DiagOpts.Remarks.size(); I != N; ++I) 1161 AddString(DiagOpts.Remarks[I], Record); 1162 // Note: we don't serialize the log or serialization file names, because they 1163 // are generally transient files and will almost always be overridden. 1164 Stream.EmitRecord(DIAGNOSTIC_OPTIONS, Record); 1165 Record.clear(); 1166 1167 // Write out the diagnostic/pragma mappings. 1168 WritePragmaDiagnosticMappings(Diags, /* isModule = */ WritingModule); 1169 1170 // Header search entry usage. 1171 auto HSEntryUsage = PP.getHeaderSearchInfo().computeUserEntryUsage(); 1172 auto Abbrev = std::make_shared<BitCodeAbbrev>(); 1173 Abbrev->Add(BitCodeAbbrevOp(HEADER_SEARCH_ENTRY_USAGE)); 1174 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // Number of bits. 1175 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Bit vector. 1176 unsigned HSUsageAbbrevCode = Stream.EmitAbbrev(std::move(Abbrev)); 1177 { 1178 RecordData::value_type Record[] = {HEADER_SEARCH_ENTRY_USAGE, 1179 HSEntryUsage.size()}; 1180 Stream.EmitRecordWithBlob(HSUsageAbbrevCode, Record, bytes(HSEntryUsage)); 1181 } 1182 1183 // Leave the options block. 1184 Stream.ExitBlock(); 1185 return Signature; 1186 } 1187 1188 /// Write the control block. 1189 void ASTWriter::WriteControlBlock(Preprocessor &PP, ASTContext &Context, 1190 StringRef isysroot, 1191 const std::string &OutputFile) { 1192 using namespace llvm; 1193 1194 Stream.EnterSubblock(CONTROL_BLOCK_ID, 5); 1195 RecordData Record; 1196 1197 // Metadata 1198 auto MetadataAbbrev = std::make_shared<BitCodeAbbrev>(); 1199 MetadataAbbrev->Add(BitCodeAbbrevOp(METADATA)); 1200 MetadataAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 16)); // Major 1201 MetadataAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 16)); // Minor 1202 MetadataAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 16)); // Clang maj. 1203 MetadataAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 16)); // Clang min. 1204 MetadataAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Relocatable 1205 MetadataAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Timestamps 1206 MetadataAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Errors 1207 MetadataAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // SVN branch/tag 1208 unsigned MetadataAbbrevCode = Stream.EmitAbbrev(std::move(MetadataAbbrev)); 1209 assert((!WritingModule || isysroot.empty()) && 1210 "writing module as a relocatable PCH?"); 1211 { 1212 RecordData::value_type Record[] = { 1213 METADATA, 1214 VERSION_MAJOR, 1215 VERSION_MINOR, 1216 CLANG_VERSION_MAJOR, 1217 CLANG_VERSION_MINOR, 1218 !isysroot.empty(), 1219 IncludeTimestamps, 1220 ASTHasCompilerErrors}; 1221 Stream.EmitRecordWithBlob(MetadataAbbrevCode, Record, 1222 getClangFullRepositoryVersion()); 1223 } 1224 1225 if (WritingModule) { 1226 // Module name 1227 auto Abbrev = std::make_shared<BitCodeAbbrev>(); 1228 Abbrev->Add(BitCodeAbbrevOp(MODULE_NAME)); 1229 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name 1230 unsigned AbbrevCode = Stream.EmitAbbrev(std::move(Abbrev)); 1231 RecordData::value_type Record[] = {MODULE_NAME}; 1232 Stream.EmitRecordWithBlob(AbbrevCode, Record, WritingModule->Name); 1233 } 1234 1235 if (WritingModule && WritingModule->Directory) { 1236 SmallString<128> BaseDir; 1237 if (PP.getHeaderSearchInfo().getHeaderSearchOpts().ModuleFileHomeIsCwd) { 1238 // Use the current working directory as the base path for all inputs. 1239 auto *CWD = 1240 Context.getSourceManager().getFileManager().getDirectory(".").get(); 1241 BaseDir.assign(CWD->getName()); 1242 } else { 1243 BaseDir.assign(WritingModule->Directory->getName()); 1244 } 1245 cleanPathForOutput(Context.getSourceManager().getFileManager(), BaseDir); 1246 1247 // If the home of the module is the current working directory, then we 1248 // want to pick up the cwd of the build process loading the module, not 1249 // our cwd, when we load this module. 1250 if (!(PP.getHeaderSearchInfo() 1251 .getHeaderSearchOpts() 1252 .ModuleMapFileHomeIsCwd || 1253 PP.getHeaderSearchInfo().getHeaderSearchOpts().ModuleFileHomeIsCwd) || 1254 WritingModule->Directory->getName() != StringRef(".")) { 1255 // Module directory. 1256 auto Abbrev = std::make_shared<BitCodeAbbrev>(); 1257 Abbrev->Add(BitCodeAbbrevOp(MODULE_DIRECTORY)); 1258 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Directory 1259 unsigned AbbrevCode = Stream.EmitAbbrev(std::move(Abbrev)); 1260 1261 RecordData::value_type Record[] = {MODULE_DIRECTORY}; 1262 Stream.EmitRecordWithBlob(AbbrevCode, Record, BaseDir); 1263 } 1264 1265 // Write out all other paths relative to the base directory if possible. 1266 BaseDirectory.assign(BaseDir.begin(), BaseDir.end()); 1267 } else if (!isysroot.empty()) { 1268 // Write out paths relative to the sysroot if possible. 1269 BaseDirectory = std::string(isysroot); 1270 } 1271 1272 // Module map file 1273 if (WritingModule && WritingModule->Kind == Module::ModuleMapModule) { 1274 Record.clear(); 1275 1276 auto &Map = PP.getHeaderSearchInfo().getModuleMap(); 1277 AddPath(WritingModule->PresumedModuleMapFile.empty() 1278 ? Map.getModuleMapFileForUniquing(WritingModule)->getName() 1279 : StringRef(WritingModule->PresumedModuleMapFile), 1280 Record); 1281 1282 // Additional module map files. 1283 if (auto *AdditionalModMaps = 1284 Map.getAdditionalModuleMapFiles(WritingModule)) { 1285 Record.push_back(AdditionalModMaps->size()); 1286 for (const FileEntry *F : *AdditionalModMaps) 1287 AddPath(F->getName(), Record); 1288 } else { 1289 Record.push_back(0); 1290 } 1291 1292 Stream.EmitRecord(MODULE_MAP_FILE, Record); 1293 } 1294 1295 // Imports 1296 if (Chain) { 1297 serialization::ModuleManager &Mgr = Chain->getModuleManager(); 1298 Record.clear(); 1299 1300 for (ModuleFile &M : Mgr) { 1301 // Skip modules that weren't directly imported. 1302 if (!M.isDirectlyImported()) 1303 continue; 1304 1305 Record.push_back((unsigned)M.Kind); // FIXME: Stable encoding 1306 AddSourceLocation(M.ImportLoc, Record); 1307 1308 // If we have calculated signature, there is no need to store 1309 // the size or timestamp. 1310 Record.push_back(M.Signature ? 0 : M.File->getSize()); 1311 Record.push_back(M.Signature ? 0 : getTimestampForOutput(M.File)); 1312 1313 llvm::append_range(Record, M.Signature); 1314 1315 AddString(M.ModuleName, Record); 1316 AddPath(M.FileName, Record); 1317 } 1318 Stream.EmitRecord(IMPORTS, Record); 1319 } 1320 1321 // Write the options block. 1322 Stream.EnterSubblock(OPTIONS_BLOCK_ID, 4); 1323 1324 // Language options. 1325 Record.clear(); 1326 const LangOptions &LangOpts = Context.getLangOpts(); 1327 #define LANGOPT(Name, Bits, Default, Description) \ 1328 Record.push_back(LangOpts.Name); 1329 #define ENUM_LANGOPT(Name, Type, Bits, Default, Description) \ 1330 Record.push_back(static_cast<unsigned>(LangOpts.get##Name())); 1331 #include "clang/Basic/LangOptions.def" 1332 #define SANITIZER(NAME, ID) \ 1333 Record.push_back(LangOpts.Sanitize.has(SanitizerKind::ID)); 1334 #include "clang/Basic/Sanitizers.def" 1335 1336 Record.push_back(LangOpts.ModuleFeatures.size()); 1337 for (StringRef Feature : LangOpts.ModuleFeatures) 1338 AddString(Feature, Record); 1339 1340 Record.push_back((unsigned) LangOpts.ObjCRuntime.getKind()); 1341 AddVersionTuple(LangOpts.ObjCRuntime.getVersion(), Record); 1342 1343 AddString(LangOpts.CurrentModule, Record); 1344 1345 // Comment options. 1346 Record.push_back(LangOpts.CommentOpts.BlockCommandNames.size()); 1347 for (const auto &I : LangOpts.CommentOpts.BlockCommandNames) { 1348 AddString(I, Record); 1349 } 1350 Record.push_back(LangOpts.CommentOpts.ParseAllComments); 1351 1352 // OpenMP offloading options. 1353 Record.push_back(LangOpts.OMPTargetTriples.size()); 1354 for (auto &T : LangOpts.OMPTargetTriples) 1355 AddString(T.getTriple(), Record); 1356 1357 AddString(LangOpts.OMPHostIRFile, Record); 1358 1359 Stream.EmitRecord(LANGUAGE_OPTIONS, Record); 1360 1361 // Target options. 1362 Record.clear(); 1363 const TargetInfo &Target = Context.getTargetInfo(); 1364 const TargetOptions &TargetOpts = Target.getTargetOpts(); 1365 AddString(TargetOpts.Triple, Record); 1366 AddString(TargetOpts.CPU, Record); 1367 AddString(TargetOpts.TuneCPU, Record); 1368 AddString(TargetOpts.ABI, Record); 1369 Record.push_back(TargetOpts.FeaturesAsWritten.size()); 1370 for (unsigned I = 0, N = TargetOpts.FeaturesAsWritten.size(); I != N; ++I) { 1371 AddString(TargetOpts.FeaturesAsWritten[I], Record); 1372 } 1373 Record.push_back(TargetOpts.Features.size()); 1374 for (unsigned I = 0, N = TargetOpts.Features.size(); I != N; ++I) { 1375 AddString(TargetOpts.Features[I], Record); 1376 } 1377 Stream.EmitRecord(TARGET_OPTIONS, Record); 1378 1379 // File system options. 1380 Record.clear(); 1381 const FileSystemOptions &FSOpts = 1382 Context.getSourceManager().getFileManager().getFileSystemOpts(); 1383 AddString(FSOpts.WorkingDir, Record); 1384 Stream.EmitRecord(FILE_SYSTEM_OPTIONS, Record); 1385 1386 // Header search options. 1387 Record.clear(); 1388 const HeaderSearchOptions &HSOpts 1389 = PP.getHeaderSearchInfo().getHeaderSearchOpts(); 1390 AddString(HSOpts.Sysroot, Record); 1391 1392 // Include entries. 1393 Record.push_back(HSOpts.UserEntries.size()); 1394 for (unsigned I = 0, N = HSOpts.UserEntries.size(); I != N; ++I) { 1395 const HeaderSearchOptions::Entry &Entry = HSOpts.UserEntries[I]; 1396 AddString(Entry.Path, Record); 1397 Record.push_back(static_cast<unsigned>(Entry.Group)); 1398 Record.push_back(Entry.IsFramework); 1399 Record.push_back(Entry.IgnoreSysRoot); 1400 } 1401 1402 // System header prefixes. 1403 Record.push_back(HSOpts.SystemHeaderPrefixes.size()); 1404 for (unsigned I = 0, N = HSOpts.SystemHeaderPrefixes.size(); I != N; ++I) { 1405 AddString(HSOpts.SystemHeaderPrefixes[I].Prefix, Record); 1406 Record.push_back(HSOpts.SystemHeaderPrefixes[I].IsSystemHeader); 1407 } 1408 1409 AddString(HSOpts.ResourceDir, Record); 1410 AddString(HSOpts.ModuleCachePath, Record); 1411 AddString(HSOpts.ModuleUserBuildPath, Record); 1412 Record.push_back(HSOpts.DisableModuleHash); 1413 Record.push_back(HSOpts.ImplicitModuleMaps); 1414 Record.push_back(HSOpts.ModuleMapFileHomeIsCwd); 1415 Record.push_back(HSOpts.EnablePrebuiltImplicitModules); 1416 Record.push_back(HSOpts.UseBuiltinIncludes); 1417 Record.push_back(HSOpts.UseStandardSystemIncludes); 1418 Record.push_back(HSOpts.UseStandardCXXIncludes); 1419 Record.push_back(HSOpts.UseLibcxx); 1420 // Write out the specific module cache path that contains the module files. 1421 AddString(PP.getHeaderSearchInfo().getModuleCachePath(), Record); 1422 Stream.EmitRecord(HEADER_SEARCH_OPTIONS, Record); 1423 1424 // Preprocessor options. 1425 Record.clear(); 1426 const PreprocessorOptions &PPOpts = PP.getPreprocessorOpts(); 1427 1428 // Macro definitions. 1429 Record.push_back(PPOpts.Macros.size()); 1430 for (unsigned I = 0, N = PPOpts.Macros.size(); I != N; ++I) { 1431 AddString(PPOpts.Macros[I].first, Record); 1432 Record.push_back(PPOpts.Macros[I].second); 1433 } 1434 1435 // Includes 1436 Record.push_back(PPOpts.Includes.size()); 1437 for (unsigned I = 0, N = PPOpts.Includes.size(); I != N; ++I) 1438 AddString(PPOpts.Includes[I], Record); 1439 1440 // Macro includes 1441 Record.push_back(PPOpts.MacroIncludes.size()); 1442 for (unsigned I = 0, N = PPOpts.MacroIncludes.size(); I != N; ++I) 1443 AddString(PPOpts.MacroIncludes[I], Record); 1444 1445 Record.push_back(PPOpts.UsePredefines); 1446 // Detailed record is important since it is used for the module cache hash. 1447 Record.push_back(PPOpts.DetailedRecord); 1448 AddString(PPOpts.ImplicitPCHInclude, Record); 1449 Record.push_back(static_cast<unsigned>(PPOpts.ObjCXXARCStandardLibrary)); 1450 Stream.EmitRecord(PREPROCESSOR_OPTIONS, Record); 1451 1452 // Leave the options block. 1453 Stream.ExitBlock(); 1454 1455 // Original file name and file ID 1456 SourceManager &SM = Context.getSourceManager(); 1457 if (const FileEntry *MainFile = SM.getFileEntryForID(SM.getMainFileID())) { 1458 auto FileAbbrev = std::make_shared<BitCodeAbbrev>(); 1459 FileAbbrev->Add(BitCodeAbbrevOp(ORIGINAL_FILE)); 1460 FileAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // File ID 1461 FileAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // File name 1462 unsigned FileAbbrevCode = Stream.EmitAbbrev(std::move(FileAbbrev)); 1463 1464 Record.clear(); 1465 Record.push_back(ORIGINAL_FILE); 1466 Record.push_back(SM.getMainFileID().getOpaqueValue()); 1467 EmitRecordWithPath(FileAbbrevCode, Record, MainFile->getName()); 1468 } 1469 1470 Record.clear(); 1471 Record.push_back(SM.getMainFileID().getOpaqueValue()); 1472 Stream.EmitRecord(ORIGINAL_FILE_ID, Record); 1473 1474 // Original PCH directory 1475 if (!OutputFile.empty() && OutputFile != "-") { 1476 auto Abbrev = std::make_shared<BitCodeAbbrev>(); 1477 Abbrev->Add(BitCodeAbbrevOp(ORIGINAL_PCH_DIR)); 1478 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // File name 1479 unsigned AbbrevCode = Stream.EmitAbbrev(std::move(Abbrev)); 1480 1481 SmallString<128> OutputPath(OutputFile); 1482 PreparePathForOutput(OutputPath); 1483 StringRef origDir = llvm::sys::path::parent_path(OutputPath); 1484 1485 RecordData::value_type Record[] = {ORIGINAL_PCH_DIR}; 1486 Stream.EmitRecordWithBlob(AbbrevCode, Record, origDir); 1487 } 1488 1489 std::set<const FileEntry *> AffectingModuleMaps; 1490 if (WritingModule) { 1491 AffectingModuleMaps = 1492 GetAllModuleMaps(PP.getHeaderSearchInfo(), WritingModule); 1493 } 1494 1495 WriteInputFiles(Context.SourceMgr, 1496 PP.getHeaderSearchInfo().getHeaderSearchOpts(), 1497 AffectingModuleMaps); 1498 Stream.ExitBlock(); 1499 } 1500 1501 namespace { 1502 1503 /// An input file. 1504 struct InputFileEntry { 1505 const FileEntry *File; 1506 bool IsSystemFile; 1507 bool IsTransient; 1508 bool BufferOverridden; 1509 bool IsTopLevelModuleMap; 1510 uint32_t ContentHash[2]; 1511 }; 1512 1513 } // namespace 1514 1515 void ASTWriter::WriteInputFiles( 1516 SourceManager &SourceMgr, HeaderSearchOptions &HSOpts, 1517 std::set<const FileEntry *> &AffectingModuleMaps) { 1518 using namespace llvm; 1519 1520 Stream.EnterSubblock(INPUT_FILES_BLOCK_ID, 4); 1521 1522 // Create input-file abbreviation. 1523 auto IFAbbrev = std::make_shared<BitCodeAbbrev>(); 1524 IFAbbrev->Add(BitCodeAbbrevOp(INPUT_FILE)); 1525 IFAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // ID 1526 IFAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 12)); // Size 1527 IFAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 32)); // Modification time 1528 IFAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Overridden 1529 IFAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Transient 1530 IFAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Module map 1531 IFAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // File name 1532 unsigned IFAbbrevCode = Stream.EmitAbbrev(std::move(IFAbbrev)); 1533 1534 // Create input file hash abbreviation. 1535 auto IFHAbbrev = std::make_shared<BitCodeAbbrev>(); 1536 IFHAbbrev->Add(BitCodeAbbrevOp(INPUT_FILE_HASH)); 1537 IFHAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); 1538 IFHAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); 1539 unsigned IFHAbbrevCode = Stream.EmitAbbrev(std::move(IFHAbbrev)); 1540 1541 // Get all ContentCache objects for files, sorted by whether the file is a 1542 // system one or not. System files go at the back, users files at the front. 1543 std::deque<InputFileEntry> SortedFiles; 1544 for (unsigned I = 1, N = SourceMgr.local_sloc_entry_size(); I != N; ++I) { 1545 // Get this source location entry. 1546 const SrcMgr::SLocEntry *SLoc = &SourceMgr.getLocalSLocEntry(I); 1547 assert(&SourceMgr.getSLocEntry(FileID::get(I)) == SLoc); 1548 1549 // We only care about file entries that were not overridden. 1550 if (!SLoc->isFile()) 1551 continue; 1552 const SrcMgr::FileInfo &File = SLoc->getFile(); 1553 const SrcMgr::ContentCache *Cache = &File.getContentCache(); 1554 if (!Cache->OrigEntry) 1555 continue; 1556 1557 if (isModuleMap(File.getFileCharacteristic()) && 1558 !isSystem(File.getFileCharacteristic()) && 1559 !AffectingModuleMaps.empty() && 1560 AffectingModuleMaps.find(Cache->OrigEntry) == 1561 AffectingModuleMaps.end()) { 1562 SkippedModuleMaps.insert(Cache->OrigEntry); 1563 // Do not emit modulemaps that do not affect current module. 1564 continue; 1565 } 1566 1567 InputFileEntry Entry; 1568 Entry.File = Cache->OrigEntry; 1569 Entry.IsSystemFile = isSystem(File.getFileCharacteristic()); 1570 Entry.IsTransient = Cache->IsTransient; 1571 Entry.BufferOverridden = Cache->BufferOverridden; 1572 Entry.IsTopLevelModuleMap = isModuleMap(File.getFileCharacteristic()) && 1573 File.getIncludeLoc().isInvalid(); 1574 1575 auto ContentHash = hash_code(-1); 1576 if (PP->getHeaderSearchInfo() 1577 .getHeaderSearchOpts() 1578 .ValidateASTInputFilesContent) { 1579 auto MemBuff = Cache->getBufferIfLoaded(); 1580 if (MemBuff) 1581 ContentHash = hash_value(MemBuff->getBuffer()); 1582 else 1583 // FIXME: The path should be taken from the FileEntryRef. 1584 PP->Diag(SourceLocation(), diag::err_module_unable_to_hash_content) 1585 << Entry.File->getName(); 1586 } 1587 auto CH = llvm::APInt(64, ContentHash); 1588 Entry.ContentHash[0] = 1589 static_cast<uint32_t>(CH.getLoBits(32).getZExtValue()); 1590 Entry.ContentHash[1] = 1591 static_cast<uint32_t>(CH.getHiBits(32).getZExtValue()); 1592 1593 if (Entry.IsSystemFile) 1594 SortedFiles.push_back(Entry); 1595 else 1596 SortedFiles.push_front(Entry); 1597 } 1598 1599 unsigned UserFilesNum = 0; 1600 // Write out all of the input files. 1601 std::vector<uint64_t> InputFileOffsets; 1602 for (const auto &Entry : SortedFiles) { 1603 uint32_t &InputFileID = InputFileIDs[Entry.File]; 1604 if (InputFileID != 0) 1605 continue; // already recorded this file. 1606 1607 // Record this entry's offset. 1608 InputFileOffsets.push_back(Stream.GetCurrentBitNo()); 1609 1610 InputFileID = InputFileOffsets.size(); 1611 1612 if (!Entry.IsSystemFile) 1613 ++UserFilesNum; 1614 1615 // Emit size/modification time for this file. 1616 // And whether this file was overridden. 1617 { 1618 RecordData::value_type Record[] = { 1619 INPUT_FILE, 1620 InputFileOffsets.size(), 1621 (uint64_t)Entry.File->getSize(), 1622 (uint64_t)getTimestampForOutput(Entry.File), 1623 Entry.BufferOverridden, 1624 Entry.IsTransient, 1625 Entry.IsTopLevelModuleMap}; 1626 1627 // FIXME: The path should be taken from the FileEntryRef. 1628 EmitRecordWithPath(IFAbbrevCode, Record, Entry.File->getName()); 1629 } 1630 1631 // Emit content hash for this file. 1632 { 1633 RecordData::value_type Record[] = {INPUT_FILE_HASH, Entry.ContentHash[0], 1634 Entry.ContentHash[1]}; 1635 Stream.EmitRecordWithAbbrev(IFHAbbrevCode, Record); 1636 } 1637 } 1638 1639 Stream.ExitBlock(); 1640 1641 // Create input file offsets abbreviation. 1642 auto OffsetsAbbrev = std::make_shared<BitCodeAbbrev>(); 1643 OffsetsAbbrev->Add(BitCodeAbbrevOp(INPUT_FILE_OFFSETS)); 1644 OffsetsAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // # input files 1645 OffsetsAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // # non-system 1646 // input files 1647 OffsetsAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Array 1648 unsigned OffsetsAbbrevCode = Stream.EmitAbbrev(std::move(OffsetsAbbrev)); 1649 1650 // Write input file offsets. 1651 RecordData::value_type Record[] = {INPUT_FILE_OFFSETS, 1652 InputFileOffsets.size(), UserFilesNum}; 1653 Stream.EmitRecordWithBlob(OffsetsAbbrevCode, Record, bytes(InputFileOffsets)); 1654 } 1655 1656 //===----------------------------------------------------------------------===// 1657 // Source Manager Serialization 1658 //===----------------------------------------------------------------------===// 1659 1660 /// Create an abbreviation for the SLocEntry that refers to a 1661 /// file. 1662 static unsigned CreateSLocFileAbbrev(llvm::BitstreamWriter &Stream) { 1663 using namespace llvm; 1664 1665 auto Abbrev = std::make_shared<BitCodeAbbrev>(); 1666 Abbrev->Add(BitCodeAbbrevOp(SM_SLOC_FILE_ENTRY)); 1667 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Offset 1668 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Include location 1669 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 3)); // Characteristic 1670 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Line directives 1671 // FileEntry fields. 1672 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Input File ID 1673 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // NumCreatedFIDs 1674 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 24)); // FirstDeclIndex 1675 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // NumDecls 1676 return Stream.EmitAbbrev(std::move(Abbrev)); 1677 } 1678 1679 /// Create an abbreviation for the SLocEntry that refers to a 1680 /// buffer. 1681 static unsigned CreateSLocBufferAbbrev(llvm::BitstreamWriter &Stream) { 1682 using namespace llvm; 1683 1684 auto Abbrev = std::make_shared<BitCodeAbbrev>(); 1685 Abbrev->Add(BitCodeAbbrevOp(SM_SLOC_BUFFER_ENTRY)); 1686 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Offset 1687 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Include location 1688 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 3)); // Characteristic 1689 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Line directives 1690 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Buffer name blob 1691 return Stream.EmitAbbrev(std::move(Abbrev)); 1692 } 1693 1694 /// Create an abbreviation for the SLocEntry that refers to a 1695 /// buffer's blob. 1696 static unsigned CreateSLocBufferBlobAbbrev(llvm::BitstreamWriter &Stream, 1697 bool Compressed) { 1698 using namespace llvm; 1699 1700 auto Abbrev = std::make_shared<BitCodeAbbrev>(); 1701 Abbrev->Add(BitCodeAbbrevOp(Compressed ? SM_SLOC_BUFFER_BLOB_COMPRESSED 1702 : SM_SLOC_BUFFER_BLOB)); 1703 if (Compressed) 1704 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Uncompressed size 1705 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Blob 1706 return Stream.EmitAbbrev(std::move(Abbrev)); 1707 } 1708 1709 /// Create an abbreviation for the SLocEntry that refers to a macro 1710 /// expansion. 1711 static unsigned CreateSLocExpansionAbbrev(llvm::BitstreamWriter &Stream) { 1712 using namespace llvm; 1713 1714 auto Abbrev = std::make_shared<BitCodeAbbrev>(); 1715 Abbrev->Add(BitCodeAbbrevOp(SM_SLOC_EXPANSION_ENTRY)); 1716 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Offset 1717 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Spelling location 1718 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Start location 1719 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // End location 1720 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Is token range 1721 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Token length 1722 return Stream.EmitAbbrev(std::move(Abbrev)); 1723 } 1724 1725 /// Emit key length and data length as ULEB-encoded data, and return them as a 1726 /// pair. 1727 static std::pair<unsigned, unsigned> 1728 emitULEBKeyDataLength(unsigned KeyLen, unsigned DataLen, raw_ostream &Out) { 1729 llvm::encodeULEB128(KeyLen, Out); 1730 llvm::encodeULEB128(DataLen, Out); 1731 return std::make_pair(KeyLen, DataLen); 1732 } 1733 1734 namespace { 1735 1736 // Trait used for the on-disk hash table of header search information. 1737 class HeaderFileInfoTrait { 1738 ASTWriter &Writer; 1739 1740 // Keep track of the framework names we've used during serialization. 1741 SmallString<128> FrameworkStringData; 1742 llvm::StringMap<unsigned> FrameworkNameOffset; 1743 1744 public: 1745 HeaderFileInfoTrait(ASTWriter &Writer) : Writer(Writer) {} 1746 1747 struct key_type { 1748 StringRef Filename; 1749 off_t Size; 1750 time_t ModTime; 1751 }; 1752 using key_type_ref = const key_type &; 1753 1754 using UnresolvedModule = 1755 llvm::PointerIntPair<Module *, 2, ModuleMap::ModuleHeaderRole>; 1756 1757 struct data_type { 1758 const HeaderFileInfo &HFI; 1759 ArrayRef<ModuleMap::KnownHeader> KnownHeaders; 1760 UnresolvedModule Unresolved; 1761 }; 1762 using data_type_ref = const data_type &; 1763 1764 using hash_value_type = unsigned; 1765 using offset_type = unsigned; 1766 1767 hash_value_type ComputeHash(key_type_ref key) { 1768 // The hash is based only on size/time of the file, so that the reader can 1769 // match even when symlinking or excess path elements ("foo/../", "../") 1770 // change the form of the name. However, complete path is still the key. 1771 return llvm::hash_combine(key.Size, key.ModTime); 1772 } 1773 1774 std::pair<unsigned, unsigned> 1775 EmitKeyDataLength(raw_ostream& Out, key_type_ref key, data_type_ref Data) { 1776 unsigned KeyLen = key.Filename.size() + 1 + 8 + 8; 1777 unsigned DataLen = 1 + 4 + 4; 1778 for (auto ModInfo : Data.KnownHeaders) 1779 if (Writer.getLocalOrImportedSubmoduleID(ModInfo.getModule())) 1780 DataLen += 4; 1781 if (Data.Unresolved.getPointer()) 1782 DataLen += 4; 1783 return emitULEBKeyDataLength(KeyLen, DataLen, Out); 1784 } 1785 1786 void EmitKey(raw_ostream& Out, key_type_ref key, unsigned KeyLen) { 1787 using namespace llvm::support; 1788 1789 endian::Writer LE(Out, little); 1790 LE.write<uint64_t>(key.Size); 1791 KeyLen -= 8; 1792 LE.write<uint64_t>(key.ModTime); 1793 KeyLen -= 8; 1794 Out.write(key.Filename.data(), KeyLen); 1795 } 1796 1797 void EmitData(raw_ostream &Out, key_type_ref key, 1798 data_type_ref Data, unsigned DataLen) { 1799 using namespace llvm::support; 1800 1801 endian::Writer LE(Out, little); 1802 uint64_t Start = Out.tell(); (void)Start; 1803 1804 unsigned char Flags = (Data.HFI.isImport << 5) 1805 | (Data.HFI.isPragmaOnce << 4) 1806 | (Data.HFI.DirInfo << 1) 1807 | Data.HFI.IndexHeaderMapHeader; 1808 LE.write<uint8_t>(Flags); 1809 1810 if (!Data.HFI.ControllingMacro) 1811 LE.write<uint32_t>(Data.HFI.ControllingMacroID); 1812 else 1813 LE.write<uint32_t>(Writer.getIdentifierRef(Data.HFI.ControllingMacro)); 1814 1815 unsigned Offset = 0; 1816 if (!Data.HFI.Framework.empty()) { 1817 // If this header refers into a framework, save the framework name. 1818 llvm::StringMap<unsigned>::iterator Pos 1819 = FrameworkNameOffset.find(Data.HFI.Framework); 1820 if (Pos == FrameworkNameOffset.end()) { 1821 Offset = FrameworkStringData.size() + 1; 1822 FrameworkStringData.append(Data.HFI.Framework); 1823 FrameworkStringData.push_back(0); 1824 1825 FrameworkNameOffset[Data.HFI.Framework] = Offset; 1826 } else 1827 Offset = Pos->second; 1828 } 1829 LE.write<uint32_t>(Offset); 1830 1831 auto EmitModule = [&](Module *M, ModuleMap::ModuleHeaderRole Role) { 1832 if (uint32_t ModID = Writer.getLocalOrImportedSubmoduleID(M)) { 1833 uint32_t Value = (ModID << 2) | (unsigned)Role; 1834 assert((Value >> 2) == ModID && "overflow in header module info"); 1835 LE.write<uint32_t>(Value); 1836 } 1837 }; 1838 1839 // FIXME: If the header is excluded, we should write out some 1840 // record of that fact. 1841 for (auto ModInfo : Data.KnownHeaders) 1842 EmitModule(ModInfo.getModule(), ModInfo.getRole()); 1843 if (Data.Unresolved.getPointer()) 1844 EmitModule(Data.Unresolved.getPointer(), Data.Unresolved.getInt()); 1845 1846 assert(Out.tell() - Start == DataLen && "Wrong data length"); 1847 } 1848 1849 const char *strings_begin() const { return FrameworkStringData.begin(); } 1850 const char *strings_end() const { return FrameworkStringData.end(); } 1851 }; 1852 1853 } // namespace 1854 1855 /// Write the header search block for the list of files that 1856 /// 1857 /// \param HS The header search structure to save. 1858 void ASTWriter::WriteHeaderSearch(const HeaderSearch &HS) { 1859 HeaderFileInfoTrait GeneratorTrait(*this); 1860 llvm::OnDiskChainedHashTableGenerator<HeaderFileInfoTrait> Generator; 1861 SmallVector<const char *, 4> SavedStrings; 1862 unsigned NumHeaderSearchEntries = 0; 1863 1864 // Find all unresolved headers for the current module. We generally will 1865 // have resolved them before we get here, but not necessarily: we might be 1866 // compiling a preprocessed module, where there is no requirement for the 1867 // original files to exist any more. 1868 const HeaderFileInfo Empty; // So we can take a reference. 1869 if (WritingModule) { 1870 llvm::SmallVector<Module *, 16> Worklist(1, WritingModule); 1871 while (!Worklist.empty()) { 1872 Module *M = Worklist.pop_back_val(); 1873 // We don't care about headers in unimportable submodules. 1874 if (M->isUnimportable()) 1875 continue; 1876 1877 // Map to disk files where possible, to pick up any missing stat 1878 // information. This also means we don't need to check the unresolved 1879 // headers list when emitting resolved headers in the first loop below. 1880 // FIXME: It'd be preferable to avoid doing this if we were given 1881 // sufficient stat information in the module map. 1882 HS.getModuleMap().resolveHeaderDirectives(M, /*File=*/llvm::None); 1883 1884 // If the file didn't exist, we can still create a module if we were given 1885 // enough information in the module map. 1886 for (auto U : M->MissingHeaders) { 1887 // Check that we were given enough information to build a module 1888 // without this file existing on disk. 1889 if (!U.Size || (!U.ModTime && IncludeTimestamps)) { 1890 PP->Diag(U.FileNameLoc, diag::err_module_no_size_mtime_for_header) 1891 << WritingModule->getFullModuleName() << U.Size.has_value() 1892 << U.FileName; 1893 continue; 1894 } 1895 1896 // Form the effective relative pathname for the file. 1897 SmallString<128> Filename(M->Directory->getName()); 1898 llvm::sys::path::append(Filename, U.FileName); 1899 PreparePathForOutput(Filename); 1900 1901 StringRef FilenameDup = strdup(Filename.c_str()); 1902 SavedStrings.push_back(FilenameDup.data()); 1903 1904 HeaderFileInfoTrait::key_type Key = { 1905 FilenameDup, *U.Size, IncludeTimestamps ? *U.ModTime : 0 1906 }; 1907 HeaderFileInfoTrait::data_type Data = { 1908 Empty, {}, {M, ModuleMap::headerKindToRole(U.Kind)} 1909 }; 1910 // FIXME: Deal with cases where there are multiple unresolved header 1911 // directives in different submodules for the same header. 1912 Generator.insert(Key, Data, GeneratorTrait); 1913 ++NumHeaderSearchEntries; 1914 } 1915 1916 Worklist.append(M->submodule_begin(), M->submodule_end()); 1917 } 1918 } 1919 1920 SmallVector<const FileEntry *, 16> FilesByUID; 1921 HS.getFileMgr().GetUniqueIDMapping(FilesByUID); 1922 1923 if (FilesByUID.size() > HS.header_file_size()) 1924 FilesByUID.resize(HS.header_file_size()); 1925 1926 for (unsigned UID = 0, LastUID = FilesByUID.size(); UID != LastUID; ++UID) { 1927 const FileEntry *File = FilesByUID[UID]; 1928 if (!File) 1929 continue; 1930 1931 // Get the file info. This will load info from the external source if 1932 // necessary. Skip emitting this file if we have no information on it 1933 // as a header file (in which case HFI will be null) or if it hasn't 1934 // changed since it was loaded. Also skip it if it's for a modular header 1935 // from a different module; in that case, we rely on the module(s) 1936 // containing the header to provide this information. 1937 const HeaderFileInfo *HFI = 1938 HS.getExistingFileInfo(File, /*WantExternal*/!Chain); 1939 if (!HFI || (HFI->isModuleHeader && !HFI->isCompilingModuleHeader)) 1940 continue; 1941 1942 // Massage the file path into an appropriate form. 1943 StringRef Filename = File->getName(); 1944 SmallString<128> FilenameTmp(Filename); 1945 if (PreparePathForOutput(FilenameTmp)) { 1946 // If we performed any translation on the file name at all, we need to 1947 // save this string, since the generator will refer to it later. 1948 Filename = StringRef(strdup(FilenameTmp.c_str())); 1949 SavedStrings.push_back(Filename.data()); 1950 } 1951 1952 HeaderFileInfoTrait::key_type Key = { 1953 Filename, File->getSize(), getTimestampForOutput(File) 1954 }; 1955 HeaderFileInfoTrait::data_type Data = { 1956 *HFI, HS.getModuleMap().findResolvedModulesForHeader(File), {} 1957 }; 1958 Generator.insert(Key, Data, GeneratorTrait); 1959 ++NumHeaderSearchEntries; 1960 } 1961 1962 // Create the on-disk hash table in a buffer. 1963 SmallString<4096> TableData; 1964 uint32_t BucketOffset; 1965 { 1966 using namespace llvm::support; 1967 1968 llvm::raw_svector_ostream Out(TableData); 1969 // Make sure that no bucket is at offset 0 1970 endian::write<uint32_t>(Out, 0, little); 1971 BucketOffset = Generator.Emit(Out, GeneratorTrait); 1972 } 1973 1974 // Create a blob abbreviation 1975 using namespace llvm; 1976 1977 auto Abbrev = std::make_shared<BitCodeAbbrev>(); 1978 Abbrev->Add(BitCodeAbbrevOp(HEADER_SEARCH_TABLE)); 1979 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); 1980 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); 1981 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); 1982 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); 1983 unsigned TableAbbrev = Stream.EmitAbbrev(std::move(Abbrev)); 1984 1985 // Write the header search table 1986 RecordData::value_type Record[] = {HEADER_SEARCH_TABLE, BucketOffset, 1987 NumHeaderSearchEntries, TableData.size()}; 1988 TableData.append(GeneratorTrait.strings_begin(),GeneratorTrait.strings_end()); 1989 Stream.EmitRecordWithBlob(TableAbbrev, Record, TableData); 1990 1991 // Free all of the strings we had to duplicate. 1992 for (unsigned I = 0, N = SavedStrings.size(); I != N; ++I) 1993 free(const_cast<char *>(SavedStrings[I])); 1994 } 1995 1996 static void emitBlob(llvm::BitstreamWriter &Stream, StringRef Blob, 1997 unsigned SLocBufferBlobCompressedAbbrv, 1998 unsigned SLocBufferBlobAbbrv) { 1999 using RecordDataType = ASTWriter::RecordData::value_type; 2000 2001 // Compress the buffer if possible. We expect that almost all PCM 2002 // consumers will not want its contents. 2003 SmallVector<uint8_t, 0> CompressedBuffer; 2004 if (llvm::compression::zlib::isAvailable()) { 2005 llvm::compression::zlib::compress( 2006 llvm::arrayRefFromStringRef(Blob.drop_back(1)), CompressedBuffer); 2007 RecordDataType Record[] = {SM_SLOC_BUFFER_BLOB_COMPRESSED, Blob.size() - 1}; 2008 Stream.EmitRecordWithBlob(SLocBufferBlobCompressedAbbrv, Record, 2009 llvm::toStringRef(CompressedBuffer)); 2010 return; 2011 } 2012 2013 RecordDataType Record[] = {SM_SLOC_BUFFER_BLOB}; 2014 Stream.EmitRecordWithBlob(SLocBufferBlobAbbrv, Record, Blob); 2015 } 2016 2017 /// Writes the block containing the serialized form of the 2018 /// source manager. 2019 /// 2020 /// TODO: We should probably use an on-disk hash table (stored in a 2021 /// blob), indexed based on the file name, so that we only create 2022 /// entries for files that we actually need. In the common case (no 2023 /// errors), we probably won't have to create file entries for any of 2024 /// the files in the AST. 2025 void ASTWriter::WriteSourceManagerBlock(SourceManager &SourceMgr, 2026 const Preprocessor &PP) { 2027 RecordData Record; 2028 2029 // Enter the source manager block. 2030 Stream.EnterSubblock(SOURCE_MANAGER_BLOCK_ID, 4); 2031 const uint64_t SourceManagerBlockOffset = Stream.GetCurrentBitNo(); 2032 2033 // Abbreviations for the various kinds of source-location entries. 2034 unsigned SLocFileAbbrv = CreateSLocFileAbbrev(Stream); 2035 unsigned SLocBufferAbbrv = CreateSLocBufferAbbrev(Stream); 2036 unsigned SLocBufferBlobAbbrv = CreateSLocBufferBlobAbbrev(Stream, false); 2037 unsigned SLocBufferBlobCompressedAbbrv = 2038 CreateSLocBufferBlobAbbrev(Stream, true); 2039 unsigned SLocExpansionAbbrv = CreateSLocExpansionAbbrev(Stream); 2040 2041 // Write out the source location entry table. We skip the first 2042 // entry, which is always the same dummy entry. 2043 std::vector<uint32_t> SLocEntryOffsets; 2044 uint64_t SLocEntryOffsetsBase = Stream.GetCurrentBitNo(); 2045 RecordData PreloadSLocs; 2046 SLocEntryOffsets.reserve(SourceMgr.local_sloc_entry_size() - 1); 2047 for (unsigned I = 1, N = SourceMgr.local_sloc_entry_size(); 2048 I != N; ++I) { 2049 // Get this source location entry. 2050 const SrcMgr::SLocEntry *SLoc = &SourceMgr.getLocalSLocEntry(I); 2051 FileID FID = FileID::get(I); 2052 assert(&SourceMgr.getSLocEntry(FID) == SLoc); 2053 2054 // Record the offset of this source-location entry. 2055 uint64_t Offset = Stream.GetCurrentBitNo() - SLocEntryOffsetsBase; 2056 assert((Offset >> 32) == 0 && "SLocEntry offset too large"); 2057 SLocEntryOffsets.push_back(Offset); 2058 2059 // Figure out which record code to use. 2060 unsigned Code; 2061 if (SLoc->isFile()) { 2062 const SrcMgr::ContentCache *Cache = &SLoc->getFile().getContentCache(); 2063 if (Cache->OrigEntry) { 2064 Code = SM_SLOC_FILE_ENTRY; 2065 } else 2066 Code = SM_SLOC_BUFFER_ENTRY; 2067 } else 2068 Code = SM_SLOC_EXPANSION_ENTRY; 2069 Record.clear(); 2070 Record.push_back(Code); 2071 2072 // Starting offset of this entry within this module, so skip the dummy. 2073 Record.push_back(SLoc->getOffset() - 2); 2074 if (SLoc->isFile()) { 2075 const SrcMgr::FileInfo &File = SLoc->getFile(); 2076 const SrcMgr::ContentCache *Content = &File.getContentCache(); 2077 if (Content->OrigEntry && !SkippedModuleMaps.empty() && 2078 SkippedModuleMaps.find(Content->OrigEntry) != 2079 SkippedModuleMaps.end()) { 2080 // Do not emit files that were not listed as inputs. 2081 continue; 2082 } 2083 AddSourceLocation(File.getIncludeLoc(), Record); 2084 Record.push_back(File.getFileCharacteristic()); // FIXME: stable encoding 2085 Record.push_back(File.hasLineDirectives()); 2086 2087 bool EmitBlob = false; 2088 if (Content->OrigEntry) { 2089 assert(Content->OrigEntry == Content->ContentsEntry && 2090 "Writing to AST an overridden file is not supported"); 2091 2092 // The source location entry is a file. Emit input file ID. 2093 assert(InputFileIDs[Content->OrigEntry] != 0 && "Missed file entry"); 2094 Record.push_back(InputFileIDs[Content->OrigEntry]); 2095 2096 Record.push_back(File.NumCreatedFIDs); 2097 2098 FileDeclIDsTy::iterator FDI = FileDeclIDs.find(FID); 2099 if (FDI != FileDeclIDs.end()) { 2100 Record.push_back(FDI->second->FirstDeclIndex); 2101 Record.push_back(FDI->second->DeclIDs.size()); 2102 } else { 2103 Record.push_back(0); 2104 Record.push_back(0); 2105 } 2106 2107 Stream.EmitRecordWithAbbrev(SLocFileAbbrv, Record); 2108 2109 if (Content->BufferOverridden || Content->IsTransient) 2110 EmitBlob = true; 2111 } else { 2112 // The source location entry is a buffer. The blob associated 2113 // with this entry contains the contents of the buffer. 2114 2115 // We add one to the size so that we capture the trailing NULL 2116 // that is required by llvm::MemoryBuffer::getMemBuffer (on 2117 // the reader side). 2118 llvm::Optional<llvm::MemoryBufferRef> Buffer = 2119 Content->getBufferOrNone(PP.getDiagnostics(), PP.getFileManager()); 2120 StringRef Name = Buffer ? Buffer->getBufferIdentifier() : ""; 2121 Stream.EmitRecordWithBlob(SLocBufferAbbrv, Record, 2122 StringRef(Name.data(), Name.size() + 1)); 2123 EmitBlob = true; 2124 2125 if (Name == "<built-in>") 2126 PreloadSLocs.push_back(SLocEntryOffsets.size()); 2127 } 2128 2129 if (EmitBlob) { 2130 // Include the implicit terminating null character in the on-disk buffer 2131 // if we're writing it uncompressed. 2132 llvm::Optional<llvm::MemoryBufferRef> Buffer = 2133 Content->getBufferOrNone(PP.getDiagnostics(), PP.getFileManager()); 2134 if (!Buffer) 2135 Buffer = llvm::MemoryBufferRef("<<<INVALID BUFFER>>>", ""); 2136 StringRef Blob(Buffer->getBufferStart(), Buffer->getBufferSize() + 1); 2137 emitBlob(Stream, Blob, SLocBufferBlobCompressedAbbrv, 2138 SLocBufferBlobAbbrv); 2139 } 2140 } else { 2141 // The source location entry is a macro expansion. 2142 const SrcMgr::ExpansionInfo &Expansion = SLoc->getExpansion(); 2143 LocSeq::State Seq; 2144 AddSourceLocation(Expansion.getSpellingLoc(), Record, Seq); 2145 AddSourceLocation(Expansion.getExpansionLocStart(), Record, Seq); 2146 AddSourceLocation(Expansion.isMacroArgExpansion() 2147 ? SourceLocation() 2148 : Expansion.getExpansionLocEnd(), 2149 Record, Seq); 2150 Record.push_back(Expansion.isExpansionTokenRange()); 2151 2152 // Compute the token length for this macro expansion. 2153 SourceLocation::UIntTy NextOffset = SourceMgr.getNextLocalOffset(); 2154 if (I + 1 != N) 2155 NextOffset = SourceMgr.getLocalSLocEntry(I + 1).getOffset(); 2156 Record.push_back(NextOffset - SLoc->getOffset() - 1); 2157 Stream.EmitRecordWithAbbrev(SLocExpansionAbbrv, Record); 2158 } 2159 } 2160 2161 Stream.ExitBlock(); 2162 2163 if (SLocEntryOffsets.empty()) 2164 return; 2165 2166 // Write the source-location offsets table into the AST block. This 2167 // table is used for lazily loading source-location information. 2168 using namespace llvm; 2169 2170 auto Abbrev = std::make_shared<BitCodeAbbrev>(); 2171 Abbrev->Add(BitCodeAbbrevOp(SOURCE_LOCATION_OFFSETS)); 2172 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 16)); // # of slocs 2173 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 16)); // total size 2174 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 32)); // base offset 2175 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // offsets 2176 unsigned SLocOffsetsAbbrev = Stream.EmitAbbrev(std::move(Abbrev)); 2177 { 2178 RecordData::value_type Record[] = { 2179 SOURCE_LOCATION_OFFSETS, SLocEntryOffsets.size(), 2180 SourceMgr.getNextLocalOffset() - 1 /* skip dummy */, 2181 SLocEntryOffsetsBase - SourceManagerBlockOffset}; 2182 Stream.EmitRecordWithBlob(SLocOffsetsAbbrev, Record, 2183 bytes(SLocEntryOffsets)); 2184 } 2185 // Write the source location entry preloads array, telling the AST 2186 // reader which source locations entries it should load eagerly. 2187 Stream.EmitRecord(SOURCE_LOCATION_PRELOADS, PreloadSLocs); 2188 2189 // Write the line table. It depends on remapping working, so it must come 2190 // after the source location offsets. 2191 if (SourceMgr.hasLineTable()) { 2192 LineTableInfo &LineTable = SourceMgr.getLineTable(); 2193 2194 Record.clear(); 2195 2196 // Emit the needed file names. 2197 llvm::DenseMap<int, int> FilenameMap; 2198 FilenameMap[-1] = -1; // For unspecified filenames. 2199 for (const auto &L : LineTable) { 2200 if (L.first.ID < 0) 2201 continue; 2202 for (auto &LE : L.second) { 2203 if (FilenameMap.insert(std::make_pair(LE.FilenameID, 2204 FilenameMap.size() - 1)).second) 2205 AddPath(LineTable.getFilename(LE.FilenameID), Record); 2206 } 2207 } 2208 Record.push_back(0); 2209 2210 // Emit the line entries 2211 for (const auto &L : LineTable) { 2212 // Only emit entries for local files. 2213 if (L.first.ID < 0) 2214 continue; 2215 2216 // Emit the file ID 2217 Record.push_back(L.first.ID); 2218 2219 // Emit the line entries 2220 Record.push_back(L.second.size()); 2221 for (const auto &LE : L.second) { 2222 Record.push_back(LE.FileOffset); 2223 Record.push_back(LE.LineNo); 2224 Record.push_back(FilenameMap[LE.FilenameID]); 2225 Record.push_back((unsigned)LE.FileKind); 2226 Record.push_back(LE.IncludeOffset); 2227 } 2228 } 2229 2230 Stream.EmitRecord(SOURCE_MANAGER_LINE_TABLE, Record); 2231 } 2232 } 2233 2234 //===----------------------------------------------------------------------===// 2235 // Preprocessor Serialization 2236 //===----------------------------------------------------------------------===// 2237 2238 static bool shouldIgnoreMacro(MacroDirective *MD, bool IsModule, 2239 const Preprocessor &PP) { 2240 if (MacroInfo *MI = MD->getMacroInfo()) 2241 if (MI->isBuiltinMacro()) 2242 return true; 2243 2244 if (IsModule) { 2245 SourceLocation Loc = MD->getLocation(); 2246 if (Loc.isInvalid()) 2247 return true; 2248 if (PP.getSourceManager().getFileID(Loc) == PP.getPredefinesFileID()) 2249 return true; 2250 } 2251 2252 return false; 2253 } 2254 2255 void ASTWriter::writeIncludedFiles(raw_ostream &Out, const Preprocessor &PP) { 2256 using namespace llvm::support; 2257 2258 const Preprocessor::IncludedFilesSet &IncludedFiles = PP.getIncludedFiles(); 2259 2260 std::vector<uint32_t> IncludedInputFileIDs; 2261 IncludedInputFileIDs.reserve(IncludedFiles.size()); 2262 2263 for (const FileEntry *File : IncludedFiles) { 2264 auto InputFileIt = InputFileIDs.find(File); 2265 if (InputFileIt == InputFileIDs.end()) 2266 continue; 2267 IncludedInputFileIDs.push_back(InputFileIt->second); 2268 } 2269 2270 llvm::sort(IncludedInputFileIDs); 2271 2272 endian::Writer LE(Out, little); 2273 LE.write<uint32_t>(IncludedInputFileIDs.size()); 2274 for (uint32_t ID : IncludedInputFileIDs) 2275 LE.write<uint32_t>(ID); 2276 } 2277 2278 /// Writes the block containing the serialized form of the 2279 /// preprocessor. 2280 void ASTWriter::WritePreprocessor(const Preprocessor &PP, bool IsModule) { 2281 uint64_t MacroOffsetsBase = Stream.GetCurrentBitNo(); 2282 2283 PreprocessingRecord *PPRec = PP.getPreprocessingRecord(); 2284 if (PPRec) 2285 WritePreprocessorDetail(*PPRec, MacroOffsetsBase); 2286 2287 RecordData Record; 2288 RecordData ModuleMacroRecord; 2289 2290 // If the preprocessor __COUNTER__ value has been bumped, remember it. 2291 if (PP.getCounterValue() != 0) { 2292 RecordData::value_type Record[] = {PP.getCounterValue()}; 2293 Stream.EmitRecord(PP_COUNTER_VALUE, Record); 2294 } 2295 2296 // If we have a recorded #pragma assume_nonnull, remember it so it can be 2297 // replayed when the preamble terminates into the main file. 2298 SourceLocation AssumeNonNullLoc = 2299 PP.getPreambleRecordedPragmaAssumeNonNullLoc(); 2300 if (AssumeNonNullLoc.isValid()) { 2301 assert(PP.isRecordingPreamble()); 2302 AddSourceLocation(AssumeNonNullLoc, Record); 2303 Stream.EmitRecord(PP_ASSUME_NONNULL_LOC, Record); 2304 Record.clear(); 2305 } 2306 2307 if (PP.isRecordingPreamble() && PP.hasRecordedPreamble()) { 2308 assert(!IsModule); 2309 auto SkipInfo = PP.getPreambleSkipInfo(); 2310 if (SkipInfo) { 2311 Record.push_back(true); 2312 AddSourceLocation(SkipInfo->HashTokenLoc, Record); 2313 AddSourceLocation(SkipInfo->IfTokenLoc, Record); 2314 Record.push_back(SkipInfo->FoundNonSkipPortion); 2315 Record.push_back(SkipInfo->FoundElse); 2316 AddSourceLocation(SkipInfo->ElseLoc, Record); 2317 } else { 2318 Record.push_back(false); 2319 } 2320 for (const auto &Cond : PP.getPreambleConditionalStack()) { 2321 AddSourceLocation(Cond.IfLoc, Record); 2322 Record.push_back(Cond.WasSkipping); 2323 Record.push_back(Cond.FoundNonSkip); 2324 Record.push_back(Cond.FoundElse); 2325 } 2326 Stream.EmitRecord(PP_CONDITIONAL_STACK, Record); 2327 Record.clear(); 2328 } 2329 2330 // Enter the preprocessor block. 2331 Stream.EnterSubblock(PREPROCESSOR_BLOCK_ID, 3); 2332 2333 // If the AST file contains __DATE__ or __TIME__ emit a warning about this. 2334 // FIXME: Include a location for the use, and say which one was used. 2335 if (PP.SawDateOrTime()) 2336 PP.Diag(SourceLocation(), diag::warn_module_uses_date_time) << IsModule; 2337 2338 // Loop over all the macro directives that are live at the end of the file, 2339 // emitting each to the PP section. 2340 2341 // Construct the list of identifiers with macro directives that need to be 2342 // serialized. 2343 SmallVector<const IdentifierInfo *, 128> MacroIdentifiers; 2344 for (auto &Id : PP.getIdentifierTable()) 2345 if (Id.second->hadMacroDefinition() && 2346 (!Id.second->isFromAST() || 2347 Id.second->hasChangedSinceDeserialization())) 2348 MacroIdentifiers.push_back(Id.second); 2349 // Sort the set of macro definitions that need to be serialized by the 2350 // name of the macro, to provide a stable ordering. 2351 llvm::sort(MacroIdentifiers, llvm::deref<std::less<>>()); 2352 2353 // Emit the macro directives as a list and associate the offset with the 2354 // identifier they belong to. 2355 for (const IdentifierInfo *Name : MacroIdentifiers) { 2356 MacroDirective *MD = PP.getLocalMacroDirectiveHistory(Name); 2357 uint64_t StartOffset = Stream.GetCurrentBitNo() - MacroOffsetsBase; 2358 assert((StartOffset >> 32) == 0 && "Macro identifiers offset too large"); 2359 2360 // Write out any exported module macros. 2361 bool EmittedModuleMacros = false; 2362 // C+=20 Header Units are compiled module interfaces, but they preserve 2363 // macros that are live (i.e. have a defined value) at the end of the 2364 // compilation. So when writing a header unit, we preserve only the final 2365 // value of each macro (and discard any that are undefined). Header units 2366 // do not have sub-modules (although they might import other header units). 2367 // PCH files, conversely, retain the history of each macro's define/undef 2368 // and of leaf macros in sub modules. 2369 if (IsModule && WritingModule->isHeaderUnit()) { 2370 // This is for the main TU when it is a C++20 header unit. 2371 // We preserve the final state of defined macros, and we do not emit ones 2372 // that are undefined. 2373 if (!MD || shouldIgnoreMacro(MD, IsModule, PP) || 2374 MD->getKind() == MacroDirective::MD_Undefine) 2375 continue; 2376 AddSourceLocation(MD->getLocation(), Record); 2377 Record.push_back(MD->getKind()); 2378 if (auto *DefMD = dyn_cast<DefMacroDirective>(MD)) { 2379 Record.push_back(getMacroRef(DefMD->getInfo(), Name)); 2380 } else if (auto *VisMD = dyn_cast<VisibilityMacroDirective>(MD)) { 2381 Record.push_back(VisMD->isPublic()); 2382 } 2383 ModuleMacroRecord.push_back(getSubmoduleID(WritingModule)); 2384 ModuleMacroRecord.push_back(getMacroRef(MD->getMacroInfo(), Name)); 2385 Stream.EmitRecord(PP_MODULE_MACRO, ModuleMacroRecord); 2386 ModuleMacroRecord.clear(); 2387 EmittedModuleMacros = true; 2388 } else { 2389 // Emit the macro directives in reverse source order. 2390 for (; MD; MD = MD->getPrevious()) { 2391 // Once we hit an ignored macro, we're done: the rest of the chain 2392 // will all be ignored macros. 2393 if (shouldIgnoreMacro(MD, IsModule, PP)) 2394 break; 2395 AddSourceLocation(MD->getLocation(), Record); 2396 Record.push_back(MD->getKind()); 2397 if (auto *DefMD = dyn_cast<DefMacroDirective>(MD)) { 2398 Record.push_back(getMacroRef(DefMD->getInfo(), Name)); 2399 } else if (auto *VisMD = dyn_cast<VisibilityMacroDirective>(MD)) { 2400 Record.push_back(VisMD->isPublic()); 2401 } 2402 } 2403 2404 // We write out exported module macros for PCH as well. 2405 auto Leafs = PP.getLeafModuleMacros(Name); 2406 SmallVector<ModuleMacro *, 8> Worklist(Leafs.begin(), Leafs.end()); 2407 llvm::DenseMap<ModuleMacro *, unsigned> Visits; 2408 while (!Worklist.empty()) { 2409 auto *Macro = Worklist.pop_back_val(); 2410 2411 // Emit a record indicating this submodule exports this macro. 2412 ModuleMacroRecord.push_back(getSubmoduleID(Macro->getOwningModule())); 2413 ModuleMacroRecord.push_back(getMacroRef(Macro->getMacroInfo(), Name)); 2414 for (auto *M : Macro->overrides()) 2415 ModuleMacroRecord.push_back(getSubmoduleID(M->getOwningModule())); 2416 2417 Stream.EmitRecord(PP_MODULE_MACRO, ModuleMacroRecord); 2418 ModuleMacroRecord.clear(); 2419 2420 // Enqueue overridden macros once we've visited all their ancestors. 2421 for (auto *M : Macro->overrides()) 2422 if (++Visits[M] == M->getNumOverridingMacros()) 2423 Worklist.push_back(M); 2424 2425 EmittedModuleMacros = true; 2426 } 2427 } 2428 if (Record.empty() && !EmittedModuleMacros) 2429 continue; 2430 2431 IdentMacroDirectivesOffsetMap[Name] = StartOffset; 2432 Stream.EmitRecord(PP_MACRO_DIRECTIVE_HISTORY, Record); 2433 Record.clear(); 2434 } 2435 2436 /// Offsets of each of the macros into the bitstream, indexed by 2437 /// the local macro ID 2438 /// 2439 /// For each identifier that is associated with a macro, this map 2440 /// provides the offset into the bitstream where that macro is 2441 /// defined. 2442 std::vector<uint32_t> MacroOffsets; 2443 2444 for (unsigned I = 0, N = MacroInfosToEmit.size(); I != N; ++I) { 2445 const IdentifierInfo *Name = MacroInfosToEmit[I].Name; 2446 MacroInfo *MI = MacroInfosToEmit[I].MI; 2447 MacroID ID = MacroInfosToEmit[I].ID; 2448 2449 if (ID < FirstMacroID) { 2450 assert(0 && "Loaded MacroInfo entered MacroInfosToEmit ?"); 2451 continue; 2452 } 2453 2454 // Record the local offset of this macro. 2455 unsigned Index = ID - FirstMacroID; 2456 if (Index >= MacroOffsets.size()) 2457 MacroOffsets.resize(Index + 1); 2458 2459 uint64_t Offset = Stream.GetCurrentBitNo() - MacroOffsetsBase; 2460 assert((Offset >> 32) == 0 && "Macro offset too large"); 2461 MacroOffsets[Index] = Offset; 2462 2463 AddIdentifierRef(Name, Record); 2464 AddSourceLocation(MI->getDefinitionLoc(), Record); 2465 AddSourceLocation(MI->getDefinitionEndLoc(), Record); 2466 Record.push_back(MI->isUsed()); 2467 Record.push_back(MI->isUsedForHeaderGuard()); 2468 Record.push_back(MI->getNumTokens()); 2469 unsigned Code; 2470 if (MI->isObjectLike()) { 2471 Code = PP_MACRO_OBJECT_LIKE; 2472 } else { 2473 Code = PP_MACRO_FUNCTION_LIKE; 2474 2475 Record.push_back(MI->isC99Varargs()); 2476 Record.push_back(MI->isGNUVarargs()); 2477 Record.push_back(MI->hasCommaPasting()); 2478 Record.push_back(MI->getNumParams()); 2479 for (const IdentifierInfo *Param : MI->params()) 2480 AddIdentifierRef(Param, Record); 2481 } 2482 2483 // If we have a detailed preprocessing record, record the macro definition 2484 // ID that corresponds to this macro. 2485 if (PPRec) 2486 Record.push_back(MacroDefinitions[PPRec->findMacroDefinition(MI)]); 2487 2488 Stream.EmitRecord(Code, Record); 2489 Record.clear(); 2490 2491 // Emit the tokens array. 2492 for (unsigned TokNo = 0, e = MI->getNumTokens(); TokNo != e; ++TokNo) { 2493 // Note that we know that the preprocessor does not have any annotation 2494 // tokens in it because they are created by the parser, and thus can't 2495 // be in a macro definition. 2496 const Token &Tok = MI->getReplacementToken(TokNo); 2497 AddToken(Tok, Record); 2498 Stream.EmitRecord(PP_TOKEN, Record); 2499 Record.clear(); 2500 } 2501 ++NumMacros; 2502 } 2503 2504 Stream.ExitBlock(); 2505 2506 // Write the offsets table for macro IDs. 2507 using namespace llvm; 2508 2509 auto Abbrev = std::make_shared<BitCodeAbbrev>(); 2510 Abbrev->Add(BitCodeAbbrevOp(MACRO_OFFSET)); 2511 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // # of macros 2512 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // first ID 2513 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 32)); // base offset 2514 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); 2515 2516 unsigned MacroOffsetAbbrev = Stream.EmitAbbrev(std::move(Abbrev)); 2517 { 2518 RecordData::value_type Record[] = {MACRO_OFFSET, MacroOffsets.size(), 2519 FirstMacroID - NUM_PREDEF_MACRO_IDS, 2520 MacroOffsetsBase - ASTBlockStartOffset}; 2521 Stream.EmitRecordWithBlob(MacroOffsetAbbrev, Record, bytes(MacroOffsets)); 2522 } 2523 2524 { 2525 auto Abbrev = std::make_shared<BitCodeAbbrev>(); 2526 Abbrev->Add(BitCodeAbbrevOp(PP_INCLUDED_FILES)); 2527 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); 2528 unsigned IncludedFilesAbbrev = Stream.EmitAbbrev(std::move(Abbrev)); 2529 2530 SmallString<2048> Buffer; 2531 raw_svector_ostream Out(Buffer); 2532 writeIncludedFiles(Out, PP); 2533 RecordData::value_type Record[] = {PP_INCLUDED_FILES}; 2534 Stream.EmitRecordWithBlob(IncludedFilesAbbrev, Record, Buffer.data(), 2535 Buffer.size()); 2536 } 2537 } 2538 2539 void ASTWriter::WritePreprocessorDetail(PreprocessingRecord &PPRec, 2540 uint64_t MacroOffsetsBase) { 2541 if (PPRec.local_begin() == PPRec.local_end()) 2542 return; 2543 2544 SmallVector<PPEntityOffset, 64> PreprocessedEntityOffsets; 2545 2546 // Enter the preprocessor block. 2547 Stream.EnterSubblock(PREPROCESSOR_DETAIL_BLOCK_ID, 3); 2548 2549 // If the preprocessor has a preprocessing record, emit it. 2550 unsigned NumPreprocessingRecords = 0; 2551 using namespace llvm; 2552 2553 // Set up the abbreviation for 2554 unsigned InclusionAbbrev = 0; 2555 { 2556 auto Abbrev = std::make_shared<BitCodeAbbrev>(); 2557 Abbrev->Add(BitCodeAbbrevOp(PPD_INCLUSION_DIRECTIVE)); 2558 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // filename length 2559 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // in quotes 2560 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 2)); // kind 2561 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // imported module 2562 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); 2563 InclusionAbbrev = Stream.EmitAbbrev(std::move(Abbrev)); 2564 } 2565 2566 unsigned FirstPreprocessorEntityID 2567 = (Chain ? PPRec.getNumLoadedPreprocessedEntities() : 0) 2568 + NUM_PREDEF_PP_ENTITY_IDS; 2569 unsigned NextPreprocessorEntityID = FirstPreprocessorEntityID; 2570 RecordData Record; 2571 for (PreprocessingRecord::iterator E = PPRec.local_begin(), 2572 EEnd = PPRec.local_end(); 2573 E != EEnd; 2574 (void)++E, ++NumPreprocessingRecords, ++NextPreprocessorEntityID) { 2575 Record.clear(); 2576 2577 uint64_t Offset = Stream.GetCurrentBitNo() - MacroOffsetsBase; 2578 assert((Offset >> 32) == 0 && "Preprocessed entity offset too large"); 2579 PreprocessedEntityOffsets.push_back( 2580 PPEntityOffset((*E)->getSourceRange(), Offset)); 2581 2582 if (auto *MD = dyn_cast<MacroDefinitionRecord>(*E)) { 2583 // Record this macro definition's ID. 2584 MacroDefinitions[MD] = NextPreprocessorEntityID; 2585 2586 AddIdentifierRef(MD->getName(), Record); 2587 Stream.EmitRecord(PPD_MACRO_DEFINITION, Record); 2588 continue; 2589 } 2590 2591 if (auto *ME = dyn_cast<MacroExpansion>(*E)) { 2592 Record.push_back(ME->isBuiltinMacro()); 2593 if (ME->isBuiltinMacro()) 2594 AddIdentifierRef(ME->getName(), Record); 2595 else 2596 Record.push_back(MacroDefinitions[ME->getDefinition()]); 2597 Stream.EmitRecord(PPD_MACRO_EXPANSION, Record); 2598 continue; 2599 } 2600 2601 if (auto *ID = dyn_cast<InclusionDirective>(*E)) { 2602 Record.push_back(PPD_INCLUSION_DIRECTIVE); 2603 Record.push_back(ID->getFileName().size()); 2604 Record.push_back(ID->wasInQuotes()); 2605 Record.push_back(static_cast<unsigned>(ID->getKind())); 2606 Record.push_back(ID->importedModule()); 2607 SmallString<64> Buffer; 2608 Buffer += ID->getFileName(); 2609 // Check that the FileEntry is not null because it was not resolved and 2610 // we create a PCH even with compiler errors. 2611 if (ID->getFile()) 2612 Buffer += ID->getFile()->getName(); 2613 Stream.EmitRecordWithBlob(InclusionAbbrev, Record, Buffer); 2614 continue; 2615 } 2616 2617 llvm_unreachable("Unhandled PreprocessedEntity in ASTWriter"); 2618 } 2619 Stream.ExitBlock(); 2620 2621 // Write the offsets table for the preprocessing record. 2622 if (NumPreprocessingRecords > 0) { 2623 assert(PreprocessedEntityOffsets.size() == NumPreprocessingRecords); 2624 2625 // Write the offsets table for identifier IDs. 2626 using namespace llvm; 2627 2628 auto Abbrev = std::make_shared<BitCodeAbbrev>(); 2629 Abbrev->Add(BitCodeAbbrevOp(PPD_ENTITIES_OFFSETS)); 2630 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // first pp entity 2631 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); 2632 unsigned PPEOffsetAbbrev = Stream.EmitAbbrev(std::move(Abbrev)); 2633 2634 RecordData::value_type Record[] = {PPD_ENTITIES_OFFSETS, 2635 FirstPreprocessorEntityID - 2636 NUM_PREDEF_PP_ENTITY_IDS}; 2637 Stream.EmitRecordWithBlob(PPEOffsetAbbrev, Record, 2638 bytes(PreprocessedEntityOffsets)); 2639 } 2640 2641 // Write the skipped region table for the preprocessing record. 2642 ArrayRef<SourceRange> SkippedRanges = PPRec.getSkippedRanges(); 2643 if (SkippedRanges.size() > 0) { 2644 std::vector<PPSkippedRange> SerializedSkippedRanges; 2645 SerializedSkippedRanges.reserve(SkippedRanges.size()); 2646 for (auto const& Range : SkippedRanges) 2647 SerializedSkippedRanges.emplace_back(Range); 2648 2649 using namespace llvm; 2650 auto Abbrev = std::make_shared<BitCodeAbbrev>(); 2651 Abbrev->Add(BitCodeAbbrevOp(PPD_SKIPPED_RANGES)); 2652 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); 2653 unsigned PPESkippedRangeAbbrev = Stream.EmitAbbrev(std::move(Abbrev)); 2654 2655 Record.clear(); 2656 Record.push_back(PPD_SKIPPED_RANGES); 2657 Stream.EmitRecordWithBlob(PPESkippedRangeAbbrev, Record, 2658 bytes(SerializedSkippedRanges)); 2659 } 2660 } 2661 2662 unsigned ASTWriter::getLocalOrImportedSubmoduleID(const Module *Mod) { 2663 if (!Mod) 2664 return 0; 2665 2666 auto Known = SubmoduleIDs.find(Mod); 2667 if (Known != SubmoduleIDs.end()) 2668 return Known->second; 2669 2670 auto *Top = Mod->getTopLevelModule(); 2671 if (Top != WritingModule && 2672 (getLangOpts().CompilingPCH || 2673 !Top->fullModuleNameIs(StringRef(getLangOpts().CurrentModule)))) 2674 return 0; 2675 2676 return SubmoduleIDs[Mod] = NextSubmoduleID++; 2677 } 2678 2679 unsigned ASTWriter::getSubmoduleID(Module *Mod) { 2680 // FIXME: This can easily happen, if we have a reference to a submodule that 2681 // did not result in us loading a module file for that submodule. For 2682 // instance, a cross-top-level-module 'conflict' declaration will hit this. 2683 unsigned ID = getLocalOrImportedSubmoduleID(Mod); 2684 assert((ID || !Mod) && 2685 "asked for module ID for non-local, non-imported module"); 2686 return ID; 2687 } 2688 2689 /// Compute the number of modules within the given tree (including the 2690 /// given module). 2691 static unsigned getNumberOfModules(Module *Mod) { 2692 unsigned ChildModules = 0; 2693 for (auto Sub = Mod->submodule_begin(), SubEnd = Mod->submodule_end(); 2694 Sub != SubEnd; ++Sub) 2695 ChildModules += getNumberOfModules(*Sub); 2696 2697 return ChildModules + 1; 2698 } 2699 2700 void ASTWriter::WriteSubmodules(Module *WritingModule) { 2701 // Enter the submodule description block. 2702 Stream.EnterSubblock(SUBMODULE_BLOCK_ID, /*bits for abbreviations*/5); 2703 2704 // Write the abbreviations needed for the submodules block. 2705 using namespace llvm; 2706 2707 auto Abbrev = std::make_shared<BitCodeAbbrev>(); 2708 Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_DEFINITION)); 2709 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // ID 2710 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Parent 2711 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 3)); // Kind 2712 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // IsFramework 2713 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // IsExplicit 2714 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // IsSystem 2715 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // IsExternC 2716 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // InferSubmodules... 2717 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // InferExplicit... 2718 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // InferExportWild... 2719 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // ConfigMacrosExh... 2720 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // ModuleMapIsPriv... 2721 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name 2722 unsigned DefinitionAbbrev = Stream.EmitAbbrev(std::move(Abbrev)); 2723 2724 Abbrev = std::make_shared<BitCodeAbbrev>(); 2725 Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_UMBRELLA_HEADER)); 2726 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name 2727 unsigned UmbrellaAbbrev = Stream.EmitAbbrev(std::move(Abbrev)); 2728 2729 Abbrev = std::make_shared<BitCodeAbbrev>(); 2730 Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_HEADER)); 2731 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name 2732 unsigned HeaderAbbrev = Stream.EmitAbbrev(std::move(Abbrev)); 2733 2734 Abbrev = std::make_shared<BitCodeAbbrev>(); 2735 Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_TOPHEADER)); 2736 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name 2737 unsigned TopHeaderAbbrev = Stream.EmitAbbrev(std::move(Abbrev)); 2738 2739 Abbrev = std::make_shared<BitCodeAbbrev>(); 2740 Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_UMBRELLA_DIR)); 2741 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name 2742 unsigned UmbrellaDirAbbrev = Stream.EmitAbbrev(std::move(Abbrev)); 2743 2744 Abbrev = std::make_shared<BitCodeAbbrev>(); 2745 Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_REQUIRES)); 2746 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // State 2747 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Feature 2748 unsigned RequiresAbbrev = Stream.EmitAbbrev(std::move(Abbrev)); 2749 2750 Abbrev = std::make_shared<BitCodeAbbrev>(); 2751 Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_EXCLUDED_HEADER)); 2752 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name 2753 unsigned ExcludedHeaderAbbrev = Stream.EmitAbbrev(std::move(Abbrev)); 2754 2755 Abbrev = std::make_shared<BitCodeAbbrev>(); 2756 Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_TEXTUAL_HEADER)); 2757 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name 2758 unsigned TextualHeaderAbbrev = Stream.EmitAbbrev(std::move(Abbrev)); 2759 2760 Abbrev = std::make_shared<BitCodeAbbrev>(); 2761 Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_PRIVATE_HEADER)); 2762 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name 2763 unsigned PrivateHeaderAbbrev = Stream.EmitAbbrev(std::move(Abbrev)); 2764 2765 Abbrev = std::make_shared<BitCodeAbbrev>(); 2766 Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_PRIVATE_TEXTUAL_HEADER)); 2767 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name 2768 unsigned PrivateTextualHeaderAbbrev = Stream.EmitAbbrev(std::move(Abbrev)); 2769 2770 Abbrev = std::make_shared<BitCodeAbbrev>(); 2771 Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_LINK_LIBRARY)); 2772 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // IsFramework 2773 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name 2774 unsigned LinkLibraryAbbrev = Stream.EmitAbbrev(std::move(Abbrev)); 2775 2776 Abbrev = std::make_shared<BitCodeAbbrev>(); 2777 Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_CONFIG_MACRO)); 2778 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Macro name 2779 unsigned ConfigMacroAbbrev = Stream.EmitAbbrev(std::move(Abbrev)); 2780 2781 Abbrev = std::make_shared<BitCodeAbbrev>(); 2782 Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_CONFLICT)); 2783 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Other module 2784 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Message 2785 unsigned ConflictAbbrev = Stream.EmitAbbrev(std::move(Abbrev)); 2786 2787 Abbrev = std::make_shared<BitCodeAbbrev>(); 2788 Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_EXPORT_AS)); 2789 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Macro name 2790 unsigned ExportAsAbbrev = Stream.EmitAbbrev(std::move(Abbrev)); 2791 2792 // Write the submodule metadata block. 2793 RecordData::value_type Record[] = { 2794 getNumberOfModules(WritingModule), 2795 FirstSubmoduleID - NUM_PREDEF_SUBMODULE_IDS}; 2796 Stream.EmitRecord(SUBMODULE_METADATA, Record); 2797 2798 // Write all of the submodules. 2799 std::queue<Module *> Q; 2800 Q.push(WritingModule); 2801 while (!Q.empty()) { 2802 Module *Mod = Q.front(); 2803 Q.pop(); 2804 unsigned ID = getSubmoduleID(Mod); 2805 2806 uint64_t ParentID = 0; 2807 if (Mod->Parent) { 2808 assert(SubmoduleIDs[Mod->Parent] && "Submodule parent not written?"); 2809 ParentID = SubmoduleIDs[Mod->Parent]; 2810 } 2811 2812 // Emit the definition of the block. 2813 { 2814 RecordData::value_type Record[] = {SUBMODULE_DEFINITION, 2815 ID, 2816 ParentID, 2817 (RecordData::value_type)Mod->Kind, 2818 Mod->IsFramework, 2819 Mod->IsExplicit, 2820 Mod->IsSystem, 2821 Mod->IsExternC, 2822 Mod->InferSubmodules, 2823 Mod->InferExplicitSubmodules, 2824 Mod->InferExportWildcard, 2825 Mod->ConfigMacrosExhaustive, 2826 Mod->ModuleMapIsPrivate}; 2827 Stream.EmitRecordWithBlob(DefinitionAbbrev, Record, Mod->Name); 2828 } 2829 2830 // Emit the requirements. 2831 for (const auto &R : Mod->Requirements) { 2832 RecordData::value_type Record[] = {SUBMODULE_REQUIRES, R.second}; 2833 Stream.EmitRecordWithBlob(RequiresAbbrev, Record, R.first); 2834 } 2835 2836 // Emit the umbrella header, if there is one. 2837 if (auto UmbrellaHeader = Mod->getUmbrellaHeader()) { 2838 RecordData::value_type Record[] = {SUBMODULE_UMBRELLA_HEADER}; 2839 Stream.EmitRecordWithBlob(UmbrellaAbbrev, Record, 2840 UmbrellaHeader.NameAsWritten); 2841 } else if (auto UmbrellaDir = Mod->getUmbrellaDir()) { 2842 RecordData::value_type Record[] = {SUBMODULE_UMBRELLA_DIR}; 2843 Stream.EmitRecordWithBlob(UmbrellaDirAbbrev, Record, 2844 UmbrellaDir.NameAsWritten); 2845 } 2846 2847 // Emit the headers. 2848 struct { 2849 unsigned RecordKind; 2850 unsigned Abbrev; 2851 Module::HeaderKind HeaderKind; 2852 } HeaderLists[] = { 2853 {SUBMODULE_HEADER, HeaderAbbrev, Module::HK_Normal}, 2854 {SUBMODULE_TEXTUAL_HEADER, TextualHeaderAbbrev, Module::HK_Textual}, 2855 {SUBMODULE_PRIVATE_HEADER, PrivateHeaderAbbrev, Module::HK_Private}, 2856 {SUBMODULE_PRIVATE_TEXTUAL_HEADER, PrivateTextualHeaderAbbrev, 2857 Module::HK_PrivateTextual}, 2858 {SUBMODULE_EXCLUDED_HEADER, ExcludedHeaderAbbrev, Module::HK_Excluded} 2859 }; 2860 for (auto &HL : HeaderLists) { 2861 RecordData::value_type Record[] = {HL.RecordKind}; 2862 for (auto &H : Mod->Headers[HL.HeaderKind]) 2863 Stream.EmitRecordWithBlob(HL.Abbrev, Record, H.NameAsWritten); 2864 } 2865 2866 // Emit the top headers. 2867 { 2868 auto TopHeaders = Mod->getTopHeaders(PP->getFileManager()); 2869 RecordData::value_type Record[] = {SUBMODULE_TOPHEADER}; 2870 for (auto *H : TopHeaders) { 2871 SmallString<128> HeaderName(H->getName()); 2872 PreparePathForOutput(HeaderName); 2873 Stream.EmitRecordWithBlob(TopHeaderAbbrev, Record, HeaderName); 2874 } 2875 } 2876 2877 // Emit the imports. 2878 if (!Mod->Imports.empty()) { 2879 RecordData Record; 2880 for (auto *I : Mod->Imports) 2881 Record.push_back(getSubmoduleID(I)); 2882 Stream.EmitRecord(SUBMODULE_IMPORTS, Record); 2883 } 2884 2885 // Emit the exports. 2886 if (!Mod->Exports.empty()) { 2887 RecordData Record; 2888 for (const auto &E : Mod->Exports) { 2889 // FIXME: This may fail; we don't require that all exported modules 2890 // are local or imported. 2891 Record.push_back(getSubmoduleID(E.getPointer())); 2892 Record.push_back(E.getInt()); 2893 } 2894 Stream.EmitRecord(SUBMODULE_EXPORTS, Record); 2895 } 2896 2897 //FIXME: How do we emit the 'use'd modules? They may not be submodules. 2898 // Might be unnecessary as use declarations are only used to build the 2899 // module itself. 2900 2901 // TODO: Consider serializing undeclared uses of modules. 2902 2903 // Emit the link libraries. 2904 for (const auto &LL : Mod->LinkLibraries) { 2905 RecordData::value_type Record[] = {SUBMODULE_LINK_LIBRARY, 2906 LL.IsFramework}; 2907 Stream.EmitRecordWithBlob(LinkLibraryAbbrev, Record, LL.Library); 2908 } 2909 2910 // Emit the conflicts. 2911 for (const auto &C : Mod->Conflicts) { 2912 // FIXME: This may fail; we don't require that all conflicting modules 2913 // are local or imported. 2914 RecordData::value_type Record[] = {SUBMODULE_CONFLICT, 2915 getSubmoduleID(C.Other)}; 2916 Stream.EmitRecordWithBlob(ConflictAbbrev, Record, C.Message); 2917 } 2918 2919 // Emit the configuration macros. 2920 for (const auto &CM : Mod->ConfigMacros) { 2921 RecordData::value_type Record[] = {SUBMODULE_CONFIG_MACRO}; 2922 Stream.EmitRecordWithBlob(ConfigMacroAbbrev, Record, CM); 2923 } 2924 2925 // Emit the initializers, if any. 2926 RecordData Inits; 2927 for (Decl *D : Context->getModuleInitializers(Mod)) 2928 Inits.push_back(GetDeclRef(D)); 2929 if (!Inits.empty()) 2930 Stream.EmitRecord(SUBMODULE_INITIALIZERS, Inits); 2931 2932 // Emit the name of the re-exported module, if any. 2933 if (!Mod->ExportAsModule.empty()) { 2934 RecordData::value_type Record[] = {SUBMODULE_EXPORT_AS}; 2935 Stream.EmitRecordWithBlob(ExportAsAbbrev, Record, Mod->ExportAsModule); 2936 } 2937 2938 // Queue up the submodules of this module. 2939 for (auto *M : Mod->submodules()) 2940 Q.push(M); 2941 } 2942 2943 Stream.ExitBlock(); 2944 2945 assert((NextSubmoduleID - FirstSubmoduleID == 2946 getNumberOfModules(WritingModule)) && 2947 "Wrong # of submodules; found a reference to a non-local, " 2948 "non-imported submodule?"); 2949 } 2950 2951 void ASTWriter::WritePragmaDiagnosticMappings(const DiagnosticsEngine &Diag, 2952 bool isModule) { 2953 llvm::SmallDenseMap<const DiagnosticsEngine::DiagState *, unsigned, 64> 2954 DiagStateIDMap; 2955 unsigned CurrID = 0; 2956 RecordData Record; 2957 2958 auto EncodeDiagStateFlags = 2959 [](const DiagnosticsEngine::DiagState *DS) -> unsigned { 2960 unsigned Result = (unsigned)DS->ExtBehavior; 2961 for (unsigned Val : 2962 {(unsigned)DS->IgnoreAllWarnings, (unsigned)DS->EnableAllWarnings, 2963 (unsigned)DS->WarningsAsErrors, (unsigned)DS->ErrorsAsFatal, 2964 (unsigned)DS->SuppressSystemWarnings}) 2965 Result = (Result << 1) | Val; 2966 return Result; 2967 }; 2968 2969 unsigned Flags = EncodeDiagStateFlags(Diag.DiagStatesByLoc.FirstDiagState); 2970 Record.push_back(Flags); 2971 2972 auto AddDiagState = [&](const DiagnosticsEngine::DiagState *State, 2973 bool IncludeNonPragmaStates) { 2974 // Ensure that the diagnostic state wasn't modified since it was created. 2975 // We will not correctly round-trip this information otherwise. 2976 assert(Flags == EncodeDiagStateFlags(State) && 2977 "diag state flags vary in single AST file"); 2978 2979 unsigned &DiagStateID = DiagStateIDMap[State]; 2980 Record.push_back(DiagStateID); 2981 2982 if (DiagStateID == 0) { 2983 DiagStateID = ++CurrID; 2984 2985 // Add a placeholder for the number of mappings. 2986 auto SizeIdx = Record.size(); 2987 Record.emplace_back(); 2988 for (const auto &I : *State) { 2989 if (I.second.isPragma() || IncludeNonPragmaStates) { 2990 Record.push_back(I.first); 2991 Record.push_back(I.second.serialize()); 2992 } 2993 } 2994 // Update the placeholder. 2995 Record[SizeIdx] = (Record.size() - SizeIdx) / 2; 2996 } 2997 }; 2998 2999 AddDiagState(Diag.DiagStatesByLoc.FirstDiagState, isModule); 3000 3001 // Reserve a spot for the number of locations with state transitions. 3002 auto NumLocationsIdx = Record.size(); 3003 Record.emplace_back(); 3004 3005 // Emit the state transitions. 3006 unsigned NumLocations = 0; 3007 for (auto &FileIDAndFile : Diag.DiagStatesByLoc.Files) { 3008 if (!FileIDAndFile.first.isValid() || 3009 !FileIDAndFile.second.HasLocalTransitions) 3010 continue; 3011 ++NumLocations; 3012 3013 SourceLocation Loc = Diag.SourceMgr->getComposedLoc(FileIDAndFile.first, 0); 3014 assert(!Loc.isInvalid() && "start loc for valid FileID is invalid"); 3015 AddSourceLocation(Loc, Record); 3016 3017 Record.push_back(FileIDAndFile.second.StateTransitions.size()); 3018 for (auto &StatePoint : FileIDAndFile.second.StateTransitions) { 3019 Record.push_back(StatePoint.Offset); 3020 AddDiagState(StatePoint.State, false); 3021 } 3022 } 3023 3024 // Backpatch the number of locations. 3025 Record[NumLocationsIdx] = NumLocations; 3026 3027 // Emit CurDiagStateLoc. Do it last in order to match source order. 3028 // 3029 // This also protects against a hypothetical corner case with simulating 3030 // -Werror settings for implicit modules in the ASTReader, where reading 3031 // CurDiagState out of context could change whether warning pragmas are 3032 // treated as errors. 3033 AddSourceLocation(Diag.DiagStatesByLoc.CurDiagStateLoc, Record); 3034 AddDiagState(Diag.DiagStatesByLoc.CurDiagState, false); 3035 3036 Stream.EmitRecord(DIAG_PRAGMA_MAPPINGS, Record); 3037 } 3038 3039 //===----------------------------------------------------------------------===// 3040 // Type Serialization 3041 //===----------------------------------------------------------------------===// 3042 3043 /// Write the representation of a type to the AST stream. 3044 void ASTWriter::WriteType(QualType T) { 3045 TypeIdx &IdxRef = TypeIdxs[T]; 3046 if (IdxRef.getIndex() == 0) // we haven't seen this type before. 3047 IdxRef = TypeIdx(NextTypeID++); 3048 TypeIdx Idx = IdxRef; 3049 3050 assert(Idx.getIndex() >= FirstTypeID && "Re-writing a type from a prior AST"); 3051 3052 // Emit the type's representation. 3053 uint64_t Offset = ASTTypeWriter(*this).write(T) - DeclTypesBlockStartOffset; 3054 3055 // Record the offset for this type. 3056 unsigned Index = Idx.getIndex() - FirstTypeID; 3057 if (TypeOffsets.size() == Index) 3058 TypeOffsets.emplace_back(Offset); 3059 else if (TypeOffsets.size() < Index) { 3060 TypeOffsets.resize(Index + 1); 3061 TypeOffsets[Index].setBitOffset(Offset); 3062 } else { 3063 llvm_unreachable("Types emitted in wrong order"); 3064 } 3065 } 3066 3067 //===----------------------------------------------------------------------===// 3068 // Declaration Serialization 3069 //===----------------------------------------------------------------------===// 3070 3071 /// Write the block containing all of the declaration IDs 3072 /// lexically declared within the given DeclContext. 3073 /// 3074 /// \returns the offset of the DECL_CONTEXT_LEXICAL block within the 3075 /// bitstream, or 0 if no block was written. 3076 uint64_t ASTWriter::WriteDeclContextLexicalBlock(ASTContext &Context, 3077 DeclContext *DC) { 3078 if (DC->decls_empty()) 3079 return 0; 3080 3081 uint64_t Offset = Stream.GetCurrentBitNo(); 3082 SmallVector<uint32_t, 128> KindDeclPairs; 3083 for (const auto *D : DC->decls()) { 3084 KindDeclPairs.push_back(D->getKind()); 3085 KindDeclPairs.push_back(GetDeclRef(D)); 3086 } 3087 3088 ++NumLexicalDeclContexts; 3089 RecordData::value_type Record[] = {DECL_CONTEXT_LEXICAL}; 3090 Stream.EmitRecordWithBlob(DeclContextLexicalAbbrev, Record, 3091 bytes(KindDeclPairs)); 3092 return Offset; 3093 } 3094 3095 void ASTWriter::WriteTypeDeclOffsets() { 3096 using namespace llvm; 3097 3098 // Write the type offsets array 3099 auto Abbrev = std::make_shared<BitCodeAbbrev>(); 3100 Abbrev->Add(BitCodeAbbrevOp(TYPE_OFFSET)); 3101 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // # of types 3102 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // base type index 3103 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // types block 3104 unsigned TypeOffsetAbbrev = Stream.EmitAbbrev(std::move(Abbrev)); 3105 { 3106 RecordData::value_type Record[] = {TYPE_OFFSET, TypeOffsets.size(), 3107 FirstTypeID - NUM_PREDEF_TYPE_IDS}; 3108 Stream.EmitRecordWithBlob(TypeOffsetAbbrev, Record, bytes(TypeOffsets)); 3109 } 3110 3111 // Write the declaration offsets array 3112 Abbrev = std::make_shared<BitCodeAbbrev>(); 3113 Abbrev->Add(BitCodeAbbrevOp(DECL_OFFSET)); 3114 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // # of declarations 3115 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // base decl ID 3116 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // declarations block 3117 unsigned DeclOffsetAbbrev = Stream.EmitAbbrev(std::move(Abbrev)); 3118 { 3119 RecordData::value_type Record[] = {DECL_OFFSET, DeclOffsets.size(), 3120 FirstDeclID - NUM_PREDEF_DECL_IDS}; 3121 Stream.EmitRecordWithBlob(DeclOffsetAbbrev, Record, bytes(DeclOffsets)); 3122 } 3123 } 3124 3125 void ASTWriter::WriteFileDeclIDsMap() { 3126 using namespace llvm; 3127 3128 SmallVector<std::pair<FileID, DeclIDInFileInfo *>, 64> SortedFileDeclIDs; 3129 SortedFileDeclIDs.reserve(FileDeclIDs.size()); 3130 for (const auto &P : FileDeclIDs) 3131 SortedFileDeclIDs.push_back(std::make_pair(P.first, P.second.get())); 3132 llvm::sort(SortedFileDeclIDs, llvm::less_first()); 3133 3134 // Join the vectors of DeclIDs from all files. 3135 SmallVector<DeclID, 256> FileGroupedDeclIDs; 3136 for (auto &FileDeclEntry : SortedFileDeclIDs) { 3137 DeclIDInFileInfo &Info = *FileDeclEntry.second; 3138 Info.FirstDeclIndex = FileGroupedDeclIDs.size(); 3139 llvm::stable_sort(Info.DeclIDs); 3140 for (auto &LocDeclEntry : Info.DeclIDs) 3141 FileGroupedDeclIDs.push_back(LocDeclEntry.second); 3142 } 3143 3144 auto Abbrev = std::make_shared<BitCodeAbbrev>(); 3145 Abbrev->Add(BitCodeAbbrevOp(FILE_SORTED_DECLS)); 3146 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); 3147 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); 3148 unsigned AbbrevCode = Stream.EmitAbbrev(std::move(Abbrev)); 3149 RecordData::value_type Record[] = {FILE_SORTED_DECLS, 3150 FileGroupedDeclIDs.size()}; 3151 Stream.EmitRecordWithBlob(AbbrevCode, Record, bytes(FileGroupedDeclIDs)); 3152 } 3153 3154 void ASTWriter::WriteComments() { 3155 Stream.EnterSubblock(COMMENTS_BLOCK_ID, 3); 3156 auto _ = llvm::make_scope_exit([this] { Stream.ExitBlock(); }); 3157 if (!PP->getPreprocessorOpts().WriteCommentListToPCH) 3158 return; 3159 RecordData Record; 3160 for (const auto &FO : Context->Comments.OrderedComments) { 3161 for (const auto &OC : FO.second) { 3162 const RawComment *I = OC.second; 3163 Record.clear(); 3164 AddSourceRange(I->getSourceRange(), Record); 3165 Record.push_back(I->getKind()); 3166 Record.push_back(I->isTrailingComment()); 3167 Record.push_back(I->isAlmostTrailingComment()); 3168 Stream.EmitRecord(COMMENTS_RAW_COMMENT, Record); 3169 } 3170 } 3171 } 3172 3173 //===----------------------------------------------------------------------===// 3174 // Global Method Pool and Selector Serialization 3175 //===----------------------------------------------------------------------===// 3176 3177 namespace { 3178 3179 // Trait used for the on-disk hash table used in the method pool. 3180 class ASTMethodPoolTrait { 3181 ASTWriter &Writer; 3182 3183 public: 3184 using key_type = Selector; 3185 using key_type_ref = key_type; 3186 3187 struct data_type { 3188 SelectorID ID; 3189 ObjCMethodList Instance, Factory; 3190 }; 3191 using data_type_ref = const data_type &; 3192 3193 using hash_value_type = unsigned; 3194 using offset_type = unsigned; 3195 3196 explicit ASTMethodPoolTrait(ASTWriter &Writer) : Writer(Writer) {} 3197 3198 static hash_value_type ComputeHash(Selector Sel) { 3199 return serialization::ComputeHash(Sel); 3200 } 3201 3202 std::pair<unsigned, unsigned> 3203 EmitKeyDataLength(raw_ostream& Out, Selector Sel, 3204 data_type_ref Methods) { 3205 unsigned KeyLen = 2 + (Sel.getNumArgs()? Sel.getNumArgs() * 4 : 4); 3206 unsigned DataLen = 4 + 2 + 2; // 2 bytes for each of the method counts 3207 for (const ObjCMethodList *Method = &Methods.Instance; Method; 3208 Method = Method->getNext()) 3209 if (ShouldWriteMethodListNode(Method)) 3210 DataLen += 4; 3211 for (const ObjCMethodList *Method = &Methods.Factory; Method; 3212 Method = Method->getNext()) 3213 if (ShouldWriteMethodListNode(Method)) 3214 DataLen += 4; 3215 return emitULEBKeyDataLength(KeyLen, DataLen, Out); 3216 } 3217 3218 void EmitKey(raw_ostream& Out, Selector Sel, unsigned) { 3219 using namespace llvm::support; 3220 3221 endian::Writer LE(Out, little); 3222 uint64_t Start = Out.tell(); 3223 assert((Start >> 32) == 0 && "Selector key offset too large"); 3224 Writer.SetSelectorOffset(Sel, Start); 3225 unsigned N = Sel.getNumArgs(); 3226 LE.write<uint16_t>(N); 3227 if (N == 0) 3228 N = 1; 3229 for (unsigned I = 0; I != N; ++I) 3230 LE.write<uint32_t>( 3231 Writer.getIdentifierRef(Sel.getIdentifierInfoForSlot(I))); 3232 } 3233 3234 void EmitData(raw_ostream& Out, key_type_ref, 3235 data_type_ref Methods, unsigned DataLen) { 3236 using namespace llvm::support; 3237 3238 endian::Writer LE(Out, little); 3239 uint64_t Start = Out.tell(); (void)Start; 3240 LE.write<uint32_t>(Methods.ID); 3241 unsigned NumInstanceMethods = 0; 3242 for (const ObjCMethodList *Method = &Methods.Instance; Method; 3243 Method = Method->getNext()) 3244 if (ShouldWriteMethodListNode(Method)) 3245 ++NumInstanceMethods; 3246 3247 unsigned NumFactoryMethods = 0; 3248 for (const ObjCMethodList *Method = &Methods.Factory; Method; 3249 Method = Method->getNext()) 3250 if (ShouldWriteMethodListNode(Method)) 3251 ++NumFactoryMethods; 3252 3253 unsigned InstanceBits = Methods.Instance.getBits(); 3254 assert(InstanceBits < 4); 3255 unsigned InstanceHasMoreThanOneDeclBit = 3256 Methods.Instance.hasMoreThanOneDecl(); 3257 unsigned FullInstanceBits = (NumInstanceMethods << 3) | 3258 (InstanceHasMoreThanOneDeclBit << 2) | 3259 InstanceBits; 3260 unsigned FactoryBits = Methods.Factory.getBits(); 3261 assert(FactoryBits < 4); 3262 unsigned FactoryHasMoreThanOneDeclBit = 3263 Methods.Factory.hasMoreThanOneDecl(); 3264 unsigned FullFactoryBits = (NumFactoryMethods << 3) | 3265 (FactoryHasMoreThanOneDeclBit << 2) | 3266 FactoryBits; 3267 LE.write<uint16_t>(FullInstanceBits); 3268 LE.write<uint16_t>(FullFactoryBits); 3269 for (const ObjCMethodList *Method = &Methods.Instance; Method; 3270 Method = Method->getNext()) 3271 if (ShouldWriteMethodListNode(Method)) 3272 LE.write<uint32_t>(Writer.getDeclID(Method->getMethod())); 3273 for (const ObjCMethodList *Method = &Methods.Factory; Method; 3274 Method = Method->getNext()) 3275 if (ShouldWriteMethodListNode(Method)) 3276 LE.write<uint32_t>(Writer.getDeclID(Method->getMethod())); 3277 3278 assert(Out.tell() - Start == DataLen && "Data length is wrong"); 3279 } 3280 3281 private: 3282 static bool ShouldWriteMethodListNode(const ObjCMethodList *Node) { 3283 return (Node->getMethod() && !Node->getMethod()->isFromASTFile()); 3284 } 3285 }; 3286 3287 } // namespace 3288 3289 /// Write ObjC data: selectors and the method pool. 3290 /// 3291 /// The method pool contains both instance and factory methods, stored 3292 /// in an on-disk hash table indexed by the selector. The hash table also 3293 /// contains an empty entry for every other selector known to Sema. 3294 void ASTWriter::WriteSelectors(Sema &SemaRef) { 3295 using namespace llvm; 3296 3297 // Do we have to do anything at all? 3298 if (SemaRef.MethodPool.empty() && SelectorIDs.empty()) 3299 return; 3300 unsigned NumTableEntries = 0; 3301 // Create and write out the blob that contains selectors and the method pool. 3302 { 3303 llvm::OnDiskChainedHashTableGenerator<ASTMethodPoolTrait> Generator; 3304 ASTMethodPoolTrait Trait(*this); 3305 3306 // Create the on-disk hash table representation. We walk through every 3307 // selector we've seen and look it up in the method pool. 3308 SelectorOffsets.resize(NextSelectorID - FirstSelectorID); 3309 for (auto &SelectorAndID : SelectorIDs) { 3310 Selector S = SelectorAndID.first; 3311 SelectorID ID = SelectorAndID.second; 3312 Sema::GlobalMethodPool::iterator F = SemaRef.MethodPool.find(S); 3313 ASTMethodPoolTrait::data_type Data = { 3314 ID, 3315 ObjCMethodList(), 3316 ObjCMethodList() 3317 }; 3318 if (F != SemaRef.MethodPool.end()) { 3319 Data.Instance = F->second.first; 3320 Data.Factory = F->second.second; 3321 } 3322 // Only write this selector if it's not in an existing AST or something 3323 // changed. 3324 if (Chain && ID < FirstSelectorID) { 3325 // Selector already exists. Did it change? 3326 bool changed = false; 3327 for (ObjCMethodList *M = &Data.Instance; M && M->getMethod(); 3328 M = M->getNext()) { 3329 if (!M->getMethod()->isFromASTFile()) { 3330 changed = true; 3331 Data.Instance = *M; 3332 break; 3333 } 3334 } 3335 for (ObjCMethodList *M = &Data.Factory; M && M->getMethod(); 3336 M = M->getNext()) { 3337 if (!M->getMethod()->isFromASTFile()) { 3338 changed = true; 3339 Data.Factory = *M; 3340 break; 3341 } 3342 } 3343 if (!changed) 3344 continue; 3345 } else if (Data.Instance.getMethod() || Data.Factory.getMethod()) { 3346 // A new method pool entry. 3347 ++NumTableEntries; 3348 } 3349 Generator.insert(S, Data, Trait); 3350 } 3351 3352 // Create the on-disk hash table in a buffer. 3353 SmallString<4096> MethodPool; 3354 uint32_t BucketOffset; 3355 { 3356 using namespace llvm::support; 3357 3358 ASTMethodPoolTrait Trait(*this); 3359 llvm::raw_svector_ostream Out(MethodPool); 3360 // Make sure that no bucket is at offset 0 3361 endian::write<uint32_t>(Out, 0, little); 3362 BucketOffset = Generator.Emit(Out, Trait); 3363 } 3364 3365 // Create a blob abbreviation 3366 auto Abbrev = std::make_shared<BitCodeAbbrev>(); 3367 Abbrev->Add(BitCodeAbbrevOp(METHOD_POOL)); 3368 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); 3369 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); 3370 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); 3371 unsigned MethodPoolAbbrev = Stream.EmitAbbrev(std::move(Abbrev)); 3372 3373 // Write the method pool 3374 { 3375 RecordData::value_type Record[] = {METHOD_POOL, BucketOffset, 3376 NumTableEntries}; 3377 Stream.EmitRecordWithBlob(MethodPoolAbbrev, Record, MethodPool); 3378 } 3379 3380 // Create a blob abbreviation for the selector table offsets. 3381 Abbrev = std::make_shared<BitCodeAbbrev>(); 3382 Abbrev->Add(BitCodeAbbrevOp(SELECTOR_OFFSETS)); 3383 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // size 3384 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // first ID 3385 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); 3386 unsigned SelectorOffsetAbbrev = Stream.EmitAbbrev(std::move(Abbrev)); 3387 3388 // Write the selector offsets table. 3389 { 3390 RecordData::value_type Record[] = { 3391 SELECTOR_OFFSETS, SelectorOffsets.size(), 3392 FirstSelectorID - NUM_PREDEF_SELECTOR_IDS}; 3393 Stream.EmitRecordWithBlob(SelectorOffsetAbbrev, Record, 3394 bytes(SelectorOffsets)); 3395 } 3396 } 3397 } 3398 3399 /// Write the selectors referenced in @selector expression into AST file. 3400 void ASTWriter::WriteReferencedSelectorsPool(Sema &SemaRef) { 3401 using namespace llvm; 3402 3403 if (SemaRef.ReferencedSelectors.empty()) 3404 return; 3405 3406 RecordData Record; 3407 ASTRecordWriter Writer(*this, Record); 3408 3409 // Note: this writes out all references even for a dependent AST. But it is 3410 // very tricky to fix, and given that @selector shouldn't really appear in 3411 // headers, probably not worth it. It's not a correctness issue. 3412 for (auto &SelectorAndLocation : SemaRef.ReferencedSelectors) { 3413 Selector Sel = SelectorAndLocation.first; 3414 SourceLocation Loc = SelectorAndLocation.second; 3415 Writer.AddSelectorRef(Sel); 3416 Writer.AddSourceLocation(Loc); 3417 } 3418 Writer.Emit(REFERENCED_SELECTOR_POOL); 3419 } 3420 3421 //===----------------------------------------------------------------------===// 3422 // Identifier Table Serialization 3423 //===----------------------------------------------------------------------===// 3424 3425 /// Determine the declaration that should be put into the name lookup table to 3426 /// represent the given declaration in this module. This is usually D itself, 3427 /// but if D was imported and merged into a local declaration, we want the most 3428 /// recent local declaration instead. The chosen declaration will be the most 3429 /// recent declaration in any module that imports this one. 3430 static NamedDecl *getDeclForLocalLookup(const LangOptions &LangOpts, 3431 NamedDecl *D) { 3432 if (!LangOpts.Modules || !D->isFromASTFile()) 3433 return D; 3434 3435 if (Decl *Redecl = D->getPreviousDecl()) { 3436 // For Redeclarable decls, a prior declaration might be local. 3437 for (; Redecl; Redecl = Redecl->getPreviousDecl()) { 3438 // If we find a local decl, we're done. 3439 if (!Redecl->isFromASTFile()) { 3440 // Exception: in very rare cases (for injected-class-names), not all 3441 // redeclarations are in the same semantic context. Skip ones in a 3442 // different context. They don't go in this lookup table at all. 3443 if (!Redecl->getDeclContext()->getRedeclContext()->Equals( 3444 D->getDeclContext()->getRedeclContext())) 3445 continue; 3446 return cast<NamedDecl>(Redecl); 3447 } 3448 3449 // If we find a decl from a (chained-)PCH stop since we won't find a 3450 // local one. 3451 if (Redecl->getOwningModuleID() == 0) 3452 break; 3453 } 3454 } else if (Decl *First = D->getCanonicalDecl()) { 3455 // For Mergeable decls, the first decl might be local. 3456 if (!First->isFromASTFile()) 3457 return cast<NamedDecl>(First); 3458 } 3459 3460 // All declarations are imported. Our most recent declaration will also be 3461 // the most recent one in anyone who imports us. 3462 return D; 3463 } 3464 3465 namespace { 3466 3467 class ASTIdentifierTableTrait { 3468 ASTWriter &Writer; 3469 Preprocessor &PP; 3470 IdentifierResolver &IdResolver; 3471 bool IsModule; 3472 bool NeedDecls; 3473 ASTWriter::RecordData *InterestingIdentifierOffsets; 3474 3475 /// Determines whether this is an "interesting" identifier that needs a 3476 /// full IdentifierInfo structure written into the hash table. Notably, this 3477 /// doesn't check whether the name has macros defined; use PublicMacroIterator 3478 /// to check that. 3479 bool isInterestingIdentifier(const IdentifierInfo *II, uint64_t MacroOffset) { 3480 if (MacroOffset || II->isPoisoned() || 3481 (!IsModule && II->getObjCOrBuiltinID()) || 3482 II->hasRevertedTokenIDToIdentifier() || 3483 (NeedDecls && II->getFETokenInfo())) 3484 return true; 3485 3486 return false; 3487 } 3488 3489 public: 3490 using key_type = IdentifierInfo *; 3491 using key_type_ref = key_type; 3492 3493 using data_type = IdentID; 3494 using data_type_ref = data_type; 3495 3496 using hash_value_type = unsigned; 3497 using offset_type = unsigned; 3498 3499 ASTIdentifierTableTrait(ASTWriter &Writer, Preprocessor &PP, 3500 IdentifierResolver &IdResolver, bool IsModule, 3501 ASTWriter::RecordData *InterestingIdentifierOffsets) 3502 : Writer(Writer), PP(PP), IdResolver(IdResolver), IsModule(IsModule), 3503 NeedDecls(!IsModule || !Writer.getLangOpts().CPlusPlus), 3504 InterestingIdentifierOffsets(InterestingIdentifierOffsets) {} 3505 3506 bool needDecls() const { return NeedDecls; } 3507 3508 static hash_value_type ComputeHash(const IdentifierInfo* II) { 3509 return llvm::djbHash(II->getName()); 3510 } 3511 3512 bool isInterestingIdentifier(const IdentifierInfo *II) { 3513 auto MacroOffset = Writer.getMacroDirectivesOffset(II); 3514 return isInterestingIdentifier(II, MacroOffset); 3515 } 3516 3517 bool isInterestingNonMacroIdentifier(const IdentifierInfo *II) { 3518 return isInterestingIdentifier(II, 0); 3519 } 3520 3521 std::pair<unsigned, unsigned> 3522 EmitKeyDataLength(raw_ostream& Out, IdentifierInfo* II, IdentID ID) { 3523 // Record the location of the identifier data. This is used when generating 3524 // the mapping from persistent IDs to strings. 3525 Writer.SetIdentifierOffset(II, Out.tell()); 3526 3527 // Emit the offset of the key/data length information to the interesting 3528 // identifiers table if necessary. 3529 if (InterestingIdentifierOffsets && isInterestingIdentifier(II)) 3530 InterestingIdentifierOffsets->push_back(Out.tell()); 3531 3532 unsigned KeyLen = II->getLength() + 1; 3533 unsigned DataLen = 4; // 4 bytes for the persistent ID << 1 3534 auto MacroOffset = Writer.getMacroDirectivesOffset(II); 3535 if (isInterestingIdentifier(II, MacroOffset)) { 3536 DataLen += 2; // 2 bytes for builtin ID 3537 DataLen += 2; // 2 bytes for flags 3538 if (MacroOffset) 3539 DataLen += 4; // MacroDirectives offset. 3540 3541 if (NeedDecls) { 3542 for (IdentifierResolver::iterator D = IdResolver.begin(II), 3543 DEnd = IdResolver.end(); 3544 D != DEnd; ++D) 3545 DataLen += 4; 3546 } 3547 } 3548 return emitULEBKeyDataLength(KeyLen, DataLen, Out); 3549 } 3550 3551 void EmitKey(raw_ostream& Out, const IdentifierInfo* II, 3552 unsigned KeyLen) { 3553 Out.write(II->getNameStart(), KeyLen); 3554 } 3555 3556 void EmitData(raw_ostream& Out, IdentifierInfo* II, 3557 IdentID ID, unsigned) { 3558 using namespace llvm::support; 3559 3560 endian::Writer LE(Out, little); 3561 3562 auto MacroOffset = Writer.getMacroDirectivesOffset(II); 3563 if (!isInterestingIdentifier(II, MacroOffset)) { 3564 LE.write<uint32_t>(ID << 1); 3565 return; 3566 } 3567 3568 LE.write<uint32_t>((ID << 1) | 0x01); 3569 uint32_t Bits = (uint32_t)II->getObjCOrBuiltinID(); 3570 assert((Bits & 0xffff) == Bits && "ObjCOrBuiltinID too big for ASTReader."); 3571 LE.write<uint16_t>(Bits); 3572 Bits = 0; 3573 bool HadMacroDefinition = MacroOffset != 0; 3574 Bits = (Bits << 1) | unsigned(HadMacroDefinition); 3575 Bits = (Bits << 1) | unsigned(II->isExtensionToken()); 3576 Bits = (Bits << 1) | unsigned(II->isPoisoned()); 3577 Bits = (Bits << 1) | unsigned(II->hasRevertedTokenIDToIdentifier()); 3578 Bits = (Bits << 1) | unsigned(II->isCPlusPlusOperatorKeyword()); 3579 LE.write<uint16_t>(Bits); 3580 3581 if (HadMacroDefinition) 3582 LE.write<uint32_t>(MacroOffset); 3583 3584 if (NeedDecls) { 3585 // Emit the declaration IDs in reverse order, because the 3586 // IdentifierResolver provides the declarations as they would be 3587 // visible (e.g., the function "stat" would come before the struct 3588 // "stat"), but the ASTReader adds declarations to the end of the list 3589 // (so we need to see the struct "stat" before the function "stat"). 3590 // Only emit declarations that aren't from a chained PCH, though. 3591 SmallVector<NamedDecl *, 16> Decls(IdResolver.begin(II), 3592 IdResolver.end()); 3593 for (NamedDecl *D : llvm::reverse(Decls)) 3594 LE.write<uint32_t>( 3595 Writer.getDeclID(getDeclForLocalLookup(PP.getLangOpts(), D))); 3596 } 3597 } 3598 }; 3599 3600 } // namespace 3601 3602 /// Write the identifier table into the AST file. 3603 /// 3604 /// The identifier table consists of a blob containing string data 3605 /// (the actual identifiers themselves) and a separate "offsets" index 3606 /// that maps identifier IDs to locations within the blob. 3607 void ASTWriter::WriteIdentifierTable(Preprocessor &PP, 3608 IdentifierResolver &IdResolver, 3609 bool IsModule) { 3610 using namespace llvm; 3611 3612 RecordData InterestingIdents; 3613 3614 // Create and write out the blob that contains the identifier 3615 // strings. 3616 { 3617 llvm::OnDiskChainedHashTableGenerator<ASTIdentifierTableTrait> Generator; 3618 ASTIdentifierTableTrait Trait( 3619 *this, PP, IdResolver, IsModule, 3620 (getLangOpts().CPlusPlus && IsModule) ? &InterestingIdents : nullptr); 3621 3622 // Look for any identifiers that were named while processing the 3623 // headers, but are otherwise not needed. We add these to the hash 3624 // table to enable checking of the predefines buffer in the case 3625 // where the user adds new macro definitions when building the AST 3626 // file. 3627 SmallVector<const IdentifierInfo *, 128> IIs; 3628 for (const auto &ID : PP.getIdentifierTable()) 3629 IIs.push_back(ID.second); 3630 // Sort the identifiers lexicographically before getting them references so 3631 // that their order is stable. 3632 llvm::sort(IIs, llvm::deref<std::less<>>()); 3633 for (const IdentifierInfo *II : IIs) 3634 if (Trait.isInterestingNonMacroIdentifier(II)) 3635 getIdentifierRef(II); 3636 3637 // Create the on-disk hash table representation. We only store offsets 3638 // for identifiers that appear here for the first time. 3639 IdentifierOffsets.resize(NextIdentID - FirstIdentID); 3640 for (auto IdentIDPair : IdentifierIDs) { 3641 auto *II = const_cast<IdentifierInfo *>(IdentIDPair.first); 3642 IdentID ID = IdentIDPair.second; 3643 assert(II && "NULL identifier in identifier table"); 3644 // Write out identifiers if either the ID is local or the identifier has 3645 // changed since it was loaded. 3646 if (ID >= FirstIdentID || !Chain || !II->isFromAST() 3647 || II->hasChangedSinceDeserialization() || 3648 (Trait.needDecls() && 3649 II->hasFETokenInfoChangedSinceDeserialization())) 3650 Generator.insert(II, ID, Trait); 3651 } 3652 3653 // Create the on-disk hash table in a buffer. 3654 SmallString<4096> IdentifierTable; 3655 uint32_t BucketOffset; 3656 { 3657 using namespace llvm::support; 3658 3659 llvm::raw_svector_ostream Out(IdentifierTable); 3660 // Make sure that no bucket is at offset 0 3661 endian::write<uint32_t>(Out, 0, little); 3662 BucketOffset = Generator.Emit(Out, Trait); 3663 } 3664 3665 // Create a blob abbreviation 3666 auto Abbrev = std::make_shared<BitCodeAbbrev>(); 3667 Abbrev->Add(BitCodeAbbrevOp(IDENTIFIER_TABLE)); 3668 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); 3669 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); 3670 unsigned IDTableAbbrev = Stream.EmitAbbrev(std::move(Abbrev)); 3671 3672 // Write the identifier table 3673 RecordData::value_type Record[] = {IDENTIFIER_TABLE, BucketOffset}; 3674 Stream.EmitRecordWithBlob(IDTableAbbrev, Record, IdentifierTable); 3675 } 3676 3677 // Write the offsets table for identifier IDs. 3678 auto Abbrev = std::make_shared<BitCodeAbbrev>(); 3679 Abbrev->Add(BitCodeAbbrevOp(IDENTIFIER_OFFSET)); 3680 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // # of identifiers 3681 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // first ID 3682 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); 3683 unsigned IdentifierOffsetAbbrev = Stream.EmitAbbrev(std::move(Abbrev)); 3684 3685 #ifndef NDEBUG 3686 for (unsigned I = 0, N = IdentifierOffsets.size(); I != N; ++I) 3687 assert(IdentifierOffsets[I] && "Missing identifier offset?"); 3688 #endif 3689 3690 RecordData::value_type Record[] = {IDENTIFIER_OFFSET, 3691 IdentifierOffsets.size(), 3692 FirstIdentID - NUM_PREDEF_IDENT_IDS}; 3693 Stream.EmitRecordWithBlob(IdentifierOffsetAbbrev, Record, 3694 bytes(IdentifierOffsets)); 3695 3696 // In C++, write the list of interesting identifiers (those that are 3697 // defined as macros, poisoned, or similar unusual things). 3698 if (!InterestingIdents.empty()) 3699 Stream.EmitRecord(INTERESTING_IDENTIFIERS, InterestingIdents); 3700 } 3701 3702 //===----------------------------------------------------------------------===// 3703 // DeclContext's Name Lookup Table Serialization 3704 //===----------------------------------------------------------------------===// 3705 3706 namespace { 3707 3708 // Trait used for the on-disk hash table used in the method pool. 3709 class ASTDeclContextNameLookupTrait { 3710 ASTWriter &Writer; 3711 llvm::SmallVector<DeclID, 64> DeclIDs; 3712 3713 public: 3714 using key_type = DeclarationNameKey; 3715 using key_type_ref = key_type; 3716 3717 /// A start and end index into DeclIDs, representing a sequence of decls. 3718 using data_type = std::pair<unsigned, unsigned>; 3719 using data_type_ref = const data_type &; 3720 3721 using hash_value_type = unsigned; 3722 using offset_type = unsigned; 3723 3724 explicit ASTDeclContextNameLookupTrait(ASTWriter &Writer) : Writer(Writer) {} 3725 3726 template<typename Coll> 3727 data_type getData(const Coll &Decls) { 3728 unsigned Start = DeclIDs.size(); 3729 for (NamedDecl *D : Decls) { 3730 DeclIDs.push_back( 3731 Writer.GetDeclRef(getDeclForLocalLookup(Writer.getLangOpts(), D))); 3732 } 3733 return std::make_pair(Start, DeclIDs.size()); 3734 } 3735 3736 data_type ImportData(const reader::ASTDeclContextNameLookupTrait::data_type &FromReader) { 3737 unsigned Start = DeclIDs.size(); 3738 llvm::append_range(DeclIDs, FromReader); 3739 return std::make_pair(Start, DeclIDs.size()); 3740 } 3741 3742 static bool EqualKey(key_type_ref a, key_type_ref b) { 3743 return a == b; 3744 } 3745 3746 hash_value_type ComputeHash(DeclarationNameKey Name) { 3747 return Name.getHash(); 3748 } 3749 3750 void EmitFileRef(raw_ostream &Out, ModuleFile *F) const { 3751 assert(Writer.hasChain() && 3752 "have reference to loaded module file but no chain?"); 3753 3754 using namespace llvm::support; 3755 3756 endian::write<uint32_t>(Out, Writer.getChain()->getModuleFileID(F), little); 3757 } 3758 3759 std::pair<unsigned, unsigned> EmitKeyDataLength(raw_ostream &Out, 3760 DeclarationNameKey Name, 3761 data_type_ref Lookup) { 3762 unsigned KeyLen = 1; 3763 switch (Name.getKind()) { 3764 case DeclarationName::Identifier: 3765 case DeclarationName::ObjCZeroArgSelector: 3766 case DeclarationName::ObjCOneArgSelector: 3767 case DeclarationName::ObjCMultiArgSelector: 3768 case DeclarationName::CXXLiteralOperatorName: 3769 case DeclarationName::CXXDeductionGuideName: 3770 KeyLen += 4; 3771 break; 3772 case DeclarationName::CXXOperatorName: 3773 KeyLen += 1; 3774 break; 3775 case DeclarationName::CXXConstructorName: 3776 case DeclarationName::CXXDestructorName: 3777 case DeclarationName::CXXConversionFunctionName: 3778 case DeclarationName::CXXUsingDirective: 3779 break; 3780 } 3781 3782 // 4 bytes for each DeclID. 3783 unsigned DataLen = 4 * (Lookup.second - Lookup.first); 3784 3785 return emitULEBKeyDataLength(KeyLen, DataLen, Out); 3786 } 3787 3788 void EmitKey(raw_ostream &Out, DeclarationNameKey Name, unsigned) { 3789 using namespace llvm::support; 3790 3791 endian::Writer LE(Out, little); 3792 LE.write<uint8_t>(Name.getKind()); 3793 switch (Name.getKind()) { 3794 case DeclarationName::Identifier: 3795 case DeclarationName::CXXLiteralOperatorName: 3796 case DeclarationName::CXXDeductionGuideName: 3797 LE.write<uint32_t>(Writer.getIdentifierRef(Name.getIdentifier())); 3798 return; 3799 case DeclarationName::ObjCZeroArgSelector: 3800 case DeclarationName::ObjCOneArgSelector: 3801 case DeclarationName::ObjCMultiArgSelector: 3802 LE.write<uint32_t>(Writer.getSelectorRef(Name.getSelector())); 3803 return; 3804 case DeclarationName::CXXOperatorName: 3805 assert(Name.getOperatorKind() < NUM_OVERLOADED_OPERATORS && 3806 "Invalid operator?"); 3807 LE.write<uint8_t>(Name.getOperatorKind()); 3808 return; 3809 case DeclarationName::CXXConstructorName: 3810 case DeclarationName::CXXDestructorName: 3811 case DeclarationName::CXXConversionFunctionName: 3812 case DeclarationName::CXXUsingDirective: 3813 return; 3814 } 3815 3816 llvm_unreachable("Invalid name kind?"); 3817 } 3818 3819 void EmitData(raw_ostream &Out, key_type_ref, data_type Lookup, 3820 unsigned DataLen) { 3821 using namespace llvm::support; 3822 3823 endian::Writer LE(Out, little); 3824 uint64_t Start = Out.tell(); (void)Start; 3825 for (unsigned I = Lookup.first, N = Lookup.second; I != N; ++I) 3826 LE.write<uint32_t>(DeclIDs[I]); 3827 assert(Out.tell() - Start == DataLen && "Data length is wrong"); 3828 } 3829 }; 3830 3831 } // namespace 3832 3833 bool ASTWriter::isLookupResultExternal(StoredDeclsList &Result, 3834 DeclContext *DC) { 3835 return Result.hasExternalDecls() && 3836 DC->hasNeedToReconcileExternalVisibleStorage(); 3837 } 3838 3839 bool ASTWriter::isLookupResultEntirelyExternal(StoredDeclsList &Result, 3840 DeclContext *DC) { 3841 for (auto *D : Result.getLookupResult()) 3842 if (!getDeclForLocalLookup(getLangOpts(), D)->isFromASTFile()) 3843 return false; 3844 3845 return true; 3846 } 3847 3848 void 3849 ASTWriter::GenerateNameLookupTable(const DeclContext *ConstDC, 3850 llvm::SmallVectorImpl<char> &LookupTable) { 3851 assert(!ConstDC->hasLazyLocalLexicalLookups() && 3852 !ConstDC->hasLazyExternalLexicalLookups() && 3853 "must call buildLookups first"); 3854 3855 // FIXME: We need to build the lookups table, which is logically const. 3856 auto *DC = const_cast<DeclContext*>(ConstDC); 3857 assert(DC == DC->getPrimaryContext() && "only primary DC has lookup table"); 3858 3859 // Create the on-disk hash table representation. 3860 MultiOnDiskHashTableGenerator<reader::ASTDeclContextNameLookupTrait, 3861 ASTDeclContextNameLookupTrait> Generator; 3862 ASTDeclContextNameLookupTrait Trait(*this); 3863 3864 // The first step is to collect the declaration names which we need to 3865 // serialize into the name lookup table, and to collect them in a stable 3866 // order. 3867 SmallVector<DeclarationName, 16> Names; 3868 3869 // We also build up small sets of the constructor and conversion function 3870 // names which are visible. 3871 llvm::SmallPtrSet<DeclarationName, 8> ConstructorNameSet, ConversionNameSet; 3872 3873 for (auto &Lookup : *DC->buildLookup()) { 3874 auto &Name = Lookup.first; 3875 auto &Result = Lookup.second; 3876 3877 // If there are no local declarations in our lookup result, we 3878 // don't need to write an entry for the name at all. If we can't 3879 // write out a lookup set without performing more deserialization, 3880 // just skip this entry. 3881 if (isLookupResultExternal(Result, DC) && 3882 isLookupResultEntirelyExternal(Result, DC)) 3883 continue; 3884 3885 // We also skip empty results. If any of the results could be external and 3886 // the currently available results are empty, then all of the results are 3887 // external and we skip it above. So the only way we get here with an empty 3888 // results is when no results could have been external *and* we have 3889 // external results. 3890 // 3891 // FIXME: While we might want to start emitting on-disk entries for negative 3892 // lookups into a decl context as an optimization, today we *have* to skip 3893 // them because there are names with empty lookup results in decl contexts 3894 // which we can't emit in any stable ordering: we lookup constructors and 3895 // conversion functions in the enclosing namespace scope creating empty 3896 // results for them. This in almost certainly a bug in Clang's name lookup, 3897 // but that is likely to be hard or impossible to fix and so we tolerate it 3898 // here by omitting lookups with empty results. 3899 if (Lookup.second.getLookupResult().empty()) 3900 continue; 3901 3902 switch (Lookup.first.getNameKind()) { 3903 default: 3904 Names.push_back(Lookup.first); 3905 break; 3906 3907 case DeclarationName::CXXConstructorName: 3908 assert(isa<CXXRecordDecl>(DC) && 3909 "Cannot have a constructor name outside of a class!"); 3910 ConstructorNameSet.insert(Name); 3911 break; 3912 3913 case DeclarationName::CXXConversionFunctionName: 3914 assert(isa<CXXRecordDecl>(DC) && 3915 "Cannot have a conversion function name outside of a class!"); 3916 ConversionNameSet.insert(Name); 3917 break; 3918 } 3919 } 3920 3921 // Sort the names into a stable order. 3922 llvm::sort(Names); 3923 3924 if (auto *D = dyn_cast<CXXRecordDecl>(DC)) { 3925 // We need to establish an ordering of constructor and conversion function 3926 // names, and they don't have an intrinsic ordering. 3927 3928 // First we try the easy case by forming the current context's constructor 3929 // name and adding that name first. This is a very useful optimization to 3930 // avoid walking the lexical declarations in many cases, and it also 3931 // handles the only case where a constructor name can come from some other 3932 // lexical context -- when that name is an implicit constructor merged from 3933 // another declaration in the redecl chain. Any non-implicit constructor or 3934 // conversion function which doesn't occur in all the lexical contexts 3935 // would be an ODR violation. 3936 auto ImplicitCtorName = Context->DeclarationNames.getCXXConstructorName( 3937 Context->getCanonicalType(Context->getRecordType(D))); 3938 if (ConstructorNameSet.erase(ImplicitCtorName)) 3939 Names.push_back(ImplicitCtorName); 3940 3941 // If we still have constructors or conversion functions, we walk all the 3942 // names in the decl and add the constructors and conversion functions 3943 // which are visible in the order they lexically occur within the context. 3944 if (!ConstructorNameSet.empty() || !ConversionNameSet.empty()) 3945 for (Decl *ChildD : cast<CXXRecordDecl>(DC)->decls()) 3946 if (auto *ChildND = dyn_cast<NamedDecl>(ChildD)) { 3947 auto Name = ChildND->getDeclName(); 3948 switch (Name.getNameKind()) { 3949 default: 3950 continue; 3951 3952 case DeclarationName::CXXConstructorName: 3953 if (ConstructorNameSet.erase(Name)) 3954 Names.push_back(Name); 3955 break; 3956 3957 case DeclarationName::CXXConversionFunctionName: 3958 if (ConversionNameSet.erase(Name)) 3959 Names.push_back(Name); 3960 break; 3961 } 3962 3963 if (ConstructorNameSet.empty() && ConversionNameSet.empty()) 3964 break; 3965 } 3966 3967 assert(ConstructorNameSet.empty() && "Failed to find all of the visible " 3968 "constructors by walking all the " 3969 "lexical members of the context."); 3970 assert(ConversionNameSet.empty() && "Failed to find all of the visible " 3971 "conversion functions by walking all " 3972 "the lexical members of the context."); 3973 } 3974 3975 // Next we need to do a lookup with each name into this decl context to fully 3976 // populate any results from external sources. We don't actually use the 3977 // results of these lookups because we only want to use the results after all 3978 // results have been loaded and the pointers into them will be stable. 3979 for (auto &Name : Names) 3980 DC->lookup(Name); 3981 3982 // Now we need to insert the results for each name into the hash table. For 3983 // constructor names and conversion function names, we actually need to merge 3984 // all of the results for them into one list of results each and insert 3985 // those. 3986 SmallVector<NamedDecl *, 8> ConstructorDecls; 3987 SmallVector<NamedDecl *, 8> ConversionDecls; 3988 3989 // Now loop over the names, either inserting them or appending for the two 3990 // special cases. 3991 for (auto &Name : Names) { 3992 DeclContext::lookup_result Result = DC->noload_lookup(Name); 3993 3994 switch (Name.getNameKind()) { 3995 default: 3996 Generator.insert(Name, Trait.getData(Result), Trait); 3997 break; 3998 3999 case DeclarationName::CXXConstructorName: 4000 ConstructorDecls.append(Result.begin(), Result.end()); 4001 break; 4002 4003 case DeclarationName::CXXConversionFunctionName: 4004 ConversionDecls.append(Result.begin(), Result.end()); 4005 break; 4006 } 4007 } 4008 4009 // Handle our two special cases if we ended up having any. We arbitrarily use 4010 // the first declaration's name here because the name itself isn't part of 4011 // the key, only the kind of name is used. 4012 if (!ConstructorDecls.empty()) 4013 Generator.insert(ConstructorDecls.front()->getDeclName(), 4014 Trait.getData(ConstructorDecls), Trait); 4015 if (!ConversionDecls.empty()) 4016 Generator.insert(ConversionDecls.front()->getDeclName(), 4017 Trait.getData(ConversionDecls), Trait); 4018 4019 // Create the on-disk hash table. Also emit the existing imported and 4020 // merged table if there is one. 4021 auto *Lookups = Chain ? Chain->getLoadedLookupTables(DC) : nullptr; 4022 Generator.emit(LookupTable, Trait, Lookups ? &Lookups->Table : nullptr); 4023 } 4024 4025 /// Write the block containing all of the declaration IDs 4026 /// visible from the given DeclContext. 4027 /// 4028 /// \returns the offset of the DECL_CONTEXT_VISIBLE block within the 4029 /// bitstream, or 0 if no block was written. 4030 uint64_t ASTWriter::WriteDeclContextVisibleBlock(ASTContext &Context, 4031 DeclContext *DC) { 4032 // If we imported a key declaration of this namespace, write the visible 4033 // lookup results as an update record for it rather than including them 4034 // on this declaration. We will only look at key declarations on reload. 4035 if (isa<NamespaceDecl>(DC) && Chain && 4036 Chain->getKeyDeclaration(cast<Decl>(DC))->isFromASTFile()) { 4037 // Only do this once, for the first local declaration of the namespace. 4038 for (auto *Prev = cast<NamespaceDecl>(DC)->getPreviousDecl(); Prev; 4039 Prev = Prev->getPreviousDecl()) 4040 if (!Prev->isFromASTFile()) 4041 return 0; 4042 4043 // Note that we need to emit an update record for the primary context. 4044 UpdatedDeclContexts.insert(DC->getPrimaryContext()); 4045 4046 // Make sure all visible decls are written. They will be recorded later. We 4047 // do this using a side data structure so we can sort the names into 4048 // a deterministic order. 4049 StoredDeclsMap *Map = DC->getPrimaryContext()->buildLookup(); 4050 SmallVector<std::pair<DeclarationName, DeclContext::lookup_result>, 16> 4051 LookupResults; 4052 if (Map) { 4053 LookupResults.reserve(Map->size()); 4054 for (auto &Entry : *Map) 4055 LookupResults.push_back( 4056 std::make_pair(Entry.first, Entry.second.getLookupResult())); 4057 } 4058 4059 llvm::sort(LookupResults, llvm::less_first()); 4060 for (auto &NameAndResult : LookupResults) { 4061 DeclarationName Name = NameAndResult.first; 4062 DeclContext::lookup_result Result = NameAndResult.second; 4063 if (Name.getNameKind() == DeclarationName::CXXConstructorName || 4064 Name.getNameKind() == DeclarationName::CXXConversionFunctionName) { 4065 // We have to work around a name lookup bug here where negative lookup 4066 // results for these names get cached in namespace lookup tables (these 4067 // names should never be looked up in a namespace). 4068 assert(Result.empty() && "Cannot have a constructor or conversion " 4069 "function name in a namespace!"); 4070 continue; 4071 } 4072 4073 for (NamedDecl *ND : Result) 4074 if (!ND->isFromASTFile()) 4075 GetDeclRef(ND); 4076 } 4077 4078 return 0; 4079 } 4080 4081 if (DC->getPrimaryContext() != DC) 4082 return 0; 4083 4084 // Skip contexts which don't support name lookup. 4085 if (!DC->isLookupContext()) 4086 return 0; 4087 4088 // If not in C++, we perform name lookup for the translation unit via the 4089 // IdentifierInfo chains, don't bother to build a visible-declarations table. 4090 if (DC->isTranslationUnit() && !Context.getLangOpts().CPlusPlus) 4091 return 0; 4092 4093 // Serialize the contents of the mapping used for lookup. Note that, 4094 // although we have two very different code paths, the serialized 4095 // representation is the same for both cases: a declaration name, 4096 // followed by a size, followed by references to the visible 4097 // declarations that have that name. 4098 uint64_t Offset = Stream.GetCurrentBitNo(); 4099 StoredDeclsMap *Map = DC->buildLookup(); 4100 if (!Map || Map->empty()) 4101 return 0; 4102 4103 // Create the on-disk hash table in a buffer. 4104 SmallString<4096> LookupTable; 4105 GenerateNameLookupTable(DC, LookupTable); 4106 4107 // Write the lookup table 4108 RecordData::value_type Record[] = {DECL_CONTEXT_VISIBLE}; 4109 Stream.EmitRecordWithBlob(DeclContextVisibleLookupAbbrev, Record, 4110 LookupTable); 4111 ++NumVisibleDeclContexts; 4112 return Offset; 4113 } 4114 4115 /// Write an UPDATE_VISIBLE block for the given context. 4116 /// 4117 /// UPDATE_VISIBLE blocks contain the declarations that are added to an existing 4118 /// DeclContext in a dependent AST file. As such, they only exist for the TU 4119 /// (in C++), for namespaces, and for classes with forward-declared unscoped 4120 /// enumeration members (in C++11). 4121 void ASTWriter::WriteDeclContextVisibleUpdate(const DeclContext *DC) { 4122 StoredDeclsMap *Map = DC->getLookupPtr(); 4123 if (!Map || Map->empty()) 4124 return; 4125 4126 // Create the on-disk hash table in a buffer. 4127 SmallString<4096> LookupTable; 4128 GenerateNameLookupTable(DC, LookupTable); 4129 4130 // If we're updating a namespace, select a key declaration as the key for the 4131 // update record; those are the only ones that will be checked on reload. 4132 if (isa<NamespaceDecl>(DC)) 4133 DC = cast<DeclContext>(Chain->getKeyDeclaration(cast<Decl>(DC))); 4134 4135 // Write the lookup table 4136 RecordData::value_type Record[] = {UPDATE_VISIBLE, getDeclID(cast<Decl>(DC))}; 4137 Stream.EmitRecordWithBlob(UpdateVisibleAbbrev, Record, LookupTable); 4138 } 4139 4140 /// Write an FP_PRAGMA_OPTIONS block for the given FPOptions. 4141 void ASTWriter::WriteFPPragmaOptions(const FPOptionsOverride &Opts) { 4142 RecordData::value_type Record[] = {Opts.getAsOpaqueInt()}; 4143 Stream.EmitRecord(FP_PRAGMA_OPTIONS, Record); 4144 } 4145 4146 /// Write an OPENCL_EXTENSIONS block for the given OpenCLOptions. 4147 void ASTWriter::WriteOpenCLExtensions(Sema &SemaRef) { 4148 if (!SemaRef.Context.getLangOpts().OpenCL) 4149 return; 4150 4151 const OpenCLOptions &Opts = SemaRef.getOpenCLOptions(); 4152 RecordData Record; 4153 for (const auto &I:Opts.OptMap) { 4154 AddString(I.getKey(), Record); 4155 auto V = I.getValue(); 4156 Record.push_back(V.Supported ? 1 : 0); 4157 Record.push_back(V.Enabled ? 1 : 0); 4158 Record.push_back(V.WithPragma ? 1 : 0); 4159 Record.push_back(V.Avail); 4160 Record.push_back(V.Core); 4161 Record.push_back(V.Opt); 4162 } 4163 Stream.EmitRecord(OPENCL_EXTENSIONS, Record); 4164 } 4165 void ASTWriter::WriteCUDAPragmas(Sema &SemaRef) { 4166 if (SemaRef.ForceCUDAHostDeviceDepth > 0) { 4167 RecordData::value_type Record[] = {SemaRef.ForceCUDAHostDeviceDepth}; 4168 Stream.EmitRecord(CUDA_PRAGMA_FORCE_HOST_DEVICE_DEPTH, Record); 4169 } 4170 } 4171 4172 void ASTWriter::WriteObjCCategories() { 4173 SmallVector<ObjCCategoriesInfo, 2> CategoriesMap; 4174 RecordData Categories; 4175 4176 for (unsigned I = 0, N = ObjCClassesWithCategories.size(); I != N; ++I) { 4177 unsigned Size = 0; 4178 unsigned StartIndex = Categories.size(); 4179 4180 ObjCInterfaceDecl *Class = ObjCClassesWithCategories[I]; 4181 4182 // Allocate space for the size. 4183 Categories.push_back(0); 4184 4185 // Add the categories. 4186 for (ObjCInterfaceDecl::known_categories_iterator 4187 Cat = Class->known_categories_begin(), 4188 CatEnd = Class->known_categories_end(); 4189 Cat != CatEnd; ++Cat, ++Size) { 4190 assert(getDeclID(*Cat) != 0 && "Bogus category"); 4191 AddDeclRef(*Cat, Categories); 4192 } 4193 4194 // Update the size. 4195 Categories[StartIndex] = Size; 4196 4197 // Record this interface -> category map. 4198 ObjCCategoriesInfo CatInfo = { getDeclID(Class), StartIndex }; 4199 CategoriesMap.push_back(CatInfo); 4200 } 4201 4202 // Sort the categories map by the definition ID, since the reader will be 4203 // performing binary searches on this information. 4204 llvm::array_pod_sort(CategoriesMap.begin(), CategoriesMap.end()); 4205 4206 // Emit the categories map. 4207 using namespace llvm; 4208 4209 auto Abbrev = std::make_shared<BitCodeAbbrev>(); 4210 Abbrev->Add(BitCodeAbbrevOp(OBJC_CATEGORIES_MAP)); 4211 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // # of entries 4212 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); 4213 unsigned AbbrevID = Stream.EmitAbbrev(std::move(Abbrev)); 4214 4215 RecordData::value_type Record[] = {OBJC_CATEGORIES_MAP, CategoriesMap.size()}; 4216 Stream.EmitRecordWithBlob(AbbrevID, Record, 4217 reinterpret_cast<char *>(CategoriesMap.data()), 4218 CategoriesMap.size() * sizeof(ObjCCategoriesInfo)); 4219 4220 // Emit the category lists. 4221 Stream.EmitRecord(OBJC_CATEGORIES, Categories); 4222 } 4223 4224 void ASTWriter::WriteLateParsedTemplates(Sema &SemaRef) { 4225 Sema::LateParsedTemplateMapT &LPTMap = SemaRef.LateParsedTemplateMap; 4226 4227 if (LPTMap.empty()) 4228 return; 4229 4230 RecordData Record; 4231 for (auto &LPTMapEntry : LPTMap) { 4232 const FunctionDecl *FD = LPTMapEntry.first; 4233 LateParsedTemplate &LPT = *LPTMapEntry.second; 4234 AddDeclRef(FD, Record); 4235 AddDeclRef(LPT.D, Record); 4236 Record.push_back(LPT.Toks.size()); 4237 4238 for (const auto &Tok : LPT.Toks) { 4239 AddToken(Tok, Record); 4240 } 4241 } 4242 Stream.EmitRecord(LATE_PARSED_TEMPLATE, Record); 4243 } 4244 4245 /// Write the state of 'pragma clang optimize' at the end of the module. 4246 void ASTWriter::WriteOptimizePragmaOptions(Sema &SemaRef) { 4247 RecordData Record; 4248 SourceLocation PragmaLoc = SemaRef.getOptimizeOffPragmaLocation(); 4249 AddSourceLocation(PragmaLoc, Record); 4250 Stream.EmitRecord(OPTIMIZE_PRAGMA_OPTIONS, Record); 4251 } 4252 4253 /// Write the state of 'pragma ms_struct' at the end of the module. 4254 void ASTWriter::WriteMSStructPragmaOptions(Sema &SemaRef) { 4255 RecordData Record; 4256 Record.push_back(SemaRef.MSStructPragmaOn ? PMSST_ON : PMSST_OFF); 4257 Stream.EmitRecord(MSSTRUCT_PRAGMA_OPTIONS, Record); 4258 } 4259 4260 /// Write the state of 'pragma pointers_to_members' at the end of the 4261 //module. 4262 void ASTWriter::WriteMSPointersToMembersPragmaOptions(Sema &SemaRef) { 4263 RecordData Record; 4264 Record.push_back(SemaRef.MSPointerToMemberRepresentationMethod); 4265 AddSourceLocation(SemaRef.ImplicitMSInheritanceAttrLoc, Record); 4266 Stream.EmitRecord(POINTERS_TO_MEMBERS_PRAGMA_OPTIONS, Record); 4267 } 4268 4269 /// Write the state of 'pragma align/pack' at the end of the module. 4270 void ASTWriter::WritePackPragmaOptions(Sema &SemaRef) { 4271 // Don't serialize pragma align/pack state for modules, since it should only 4272 // take effect on a per-submodule basis. 4273 if (WritingModule) 4274 return; 4275 4276 RecordData Record; 4277 AddAlignPackInfo(SemaRef.AlignPackStack.CurrentValue, Record); 4278 AddSourceLocation(SemaRef.AlignPackStack.CurrentPragmaLocation, Record); 4279 Record.push_back(SemaRef.AlignPackStack.Stack.size()); 4280 for (const auto &StackEntry : SemaRef.AlignPackStack.Stack) { 4281 AddAlignPackInfo(StackEntry.Value, Record); 4282 AddSourceLocation(StackEntry.PragmaLocation, Record); 4283 AddSourceLocation(StackEntry.PragmaPushLocation, Record); 4284 AddString(StackEntry.StackSlotLabel, Record); 4285 } 4286 Stream.EmitRecord(ALIGN_PACK_PRAGMA_OPTIONS, Record); 4287 } 4288 4289 /// Write the state of 'pragma float_control' at the end of the module. 4290 void ASTWriter::WriteFloatControlPragmaOptions(Sema &SemaRef) { 4291 // Don't serialize pragma float_control state for modules, 4292 // since it should only take effect on a per-submodule basis. 4293 if (WritingModule) 4294 return; 4295 4296 RecordData Record; 4297 Record.push_back(SemaRef.FpPragmaStack.CurrentValue.getAsOpaqueInt()); 4298 AddSourceLocation(SemaRef.FpPragmaStack.CurrentPragmaLocation, Record); 4299 Record.push_back(SemaRef.FpPragmaStack.Stack.size()); 4300 for (const auto &StackEntry : SemaRef.FpPragmaStack.Stack) { 4301 Record.push_back(StackEntry.Value.getAsOpaqueInt()); 4302 AddSourceLocation(StackEntry.PragmaLocation, Record); 4303 AddSourceLocation(StackEntry.PragmaPushLocation, Record); 4304 AddString(StackEntry.StackSlotLabel, Record); 4305 } 4306 Stream.EmitRecord(FLOAT_CONTROL_PRAGMA_OPTIONS, Record); 4307 } 4308 4309 void ASTWriter::WriteModuleFileExtension(Sema &SemaRef, 4310 ModuleFileExtensionWriter &Writer) { 4311 // Enter the extension block. 4312 Stream.EnterSubblock(EXTENSION_BLOCK_ID, 4); 4313 4314 // Emit the metadata record abbreviation. 4315 auto Abv = std::make_shared<llvm::BitCodeAbbrev>(); 4316 Abv->Add(llvm::BitCodeAbbrevOp(EXTENSION_METADATA)); 4317 Abv->Add(llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::VBR, 6)); 4318 Abv->Add(llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::VBR, 6)); 4319 Abv->Add(llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::VBR, 6)); 4320 Abv->Add(llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::VBR, 6)); 4321 Abv->Add(llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::Blob)); 4322 unsigned Abbrev = Stream.EmitAbbrev(std::move(Abv)); 4323 4324 // Emit the metadata record. 4325 RecordData Record; 4326 auto Metadata = Writer.getExtension()->getExtensionMetadata(); 4327 Record.push_back(EXTENSION_METADATA); 4328 Record.push_back(Metadata.MajorVersion); 4329 Record.push_back(Metadata.MinorVersion); 4330 Record.push_back(Metadata.BlockName.size()); 4331 Record.push_back(Metadata.UserInfo.size()); 4332 SmallString<64> Buffer; 4333 Buffer += Metadata.BlockName; 4334 Buffer += Metadata.UserInfo; 4335 Stream.EmitRecordWithBlob(Abbrev, Record, Buffer); 4336 4337 // Emit the contents of the extension block. 4338 Writer.writeExtensionContents(SemaRef, Stream); 4339 4340 // Exit the extension block. 4341 Stream.ExitBlock(); 4342 } 4343 4344 //===----------------------------------------------------------------------===// 4345 // General Serialization Routines 4346 //===----------------------------------------------------------------------===// 4347 4348 void ASTRecordWriter::AddAttr(const Attr *A) { 4349 auto &Record = *this; 4350 // FIXME: Clang can't handle the serialization/deserialization of 4351 // preferred_name properly now. See 4352 // https://github.com/llvm/llvm-project/issues/56490 for example. 4353 if (!A || (isa<PreferredNameAttr>(A) && Writer->isWritingNamedModules())) 4354 return Record.push_back(0); 4355 4356 Record.push_back(A->getKind() + 1); // FIXME: stable encoding, target attrs 4357 4358 Record.AddIdentifierRef(A->getAttrName()); 4359 Record.AddIdentifierRef(A->getScopeName()); 4360 Record.AddSourceRange(A->getRange()); 4361 Record.AddSourceLocation(A->getScopeLoc()); 4362 Record.push_back(A->getParsedKind()); 4363 Record.push_back(A->getSyntax()); 4364 Record.push_back(A->getAttributeSpellingListIndexRaw()); 4365 4366 #include "clang/Serialization/AttrPCHWrite.inc" 4367 } 4368 4369 /// Emit the list of attributes to the specified record. 4370 void ASTRecordWriter::AddAttributes(ArrayRef<const Attr *> Attrs) { 4371 push_back(Attrs.size()); 4372 for (const auto *A : Attrs) 4373 AddAttr(A); 4374 } 4375 4376 void ASTWriter::AddToken(const Token &Tok, RecordDataImpl &Record) { 4377 AddSourceLocation(Tok.getLocation(), Record); 4378 Record.push_back(Tok.getLength()); 4379 4380 // FIXME: When reading literal tokens, reconstruct the literal pointer 4381 // if it is needed. 4382 AddIdentifierRef(Tok.getIdentifierInfo(), Record); 4383 // FIXME: Should translate token kind to a stable encoding. 4384 Record.push_back(Tok.getKind()); 4385 // FIXME: Should translate token flags to a stable encoding. 4386 Record.push_back(Tok.getFlags()); 4387 } 4388 4389 void ASTWriter::AddString(StringRef Str, RecordDataImpl &Record) { 4390 Record.push_back(Str.size()); 4391 Record.insert(Record.end(), Str.begin(), Str.end()); 4392 } 4393 4394 bool ASTWriter::PreparePathForOutput(SmallVectorImpl<char> &Path) { 4395 assert(Context && "should have context when outputting path"); 4396 4397 bool Changed = 4398 cleanPathForOutput(Context->getSourceManager().getFileManager(), Path); 4399 4400 // Remove a prefix to make the path relative, if relevant. 4401 const char *PathBegin = Path.data(); 4402 const char *PathPtr = 4403 adjustFilenameForRelocatableAST(PathBegin, BaseDirectory); 4404 if (PathPtr != PathBegin) { 4405 Path.erase(Path.begin(), Path.begin() + (PathPtr - PathBegin)); 4406 Changed = true; 4407 } 4408 4409 return Changed; 4410 } 4411 4412 void ASTWriter::AddPath(StringRef Path, RecordDataImpl &Record) { 4413 SmallString<128> FilePath(Path); 4414 PreparePathForOutput(FilePath); 4415 AddString(FilePath, Record); 4416 } 4417 4418 void ASTWriter::EmitRecordWithPath(unsigned Abbrev, RecordDataRef Record, 4419 StringRef Path) { 4420 SmallString<128> FilePath(Path); 4421 PreparePathForOutput(FilePath); 4422 Stream.EmitRecordWithBlob(Abbrev, Record, FilePath); 4423 } 4424 4425 void ASTWriter::AddVersionTuple(const VersionTuple &Version, 4426 RecordDataImpl &Record) { 4427 Record.push_back(Version.getMajor()); 4428 if (Optional<unsigned> Minor = Version.getMinor()) 4429 Record.push_back(*Minor + 1); 4430 else 4431 Record.push_back(0); 4432 if (Optional<unsigned> Subminor = Version.getSubminor()) 4433 Record.push_back(*Subminor + 1); 4434 else 4435 Record.push_back(0); 4436 } 4437 4438 /// Note that the identifier II occurs at the given offset 4439 /// within the identifier table. 4440 void ASTWriter::SetIdentifierOffset(const IdentifierInfo *II, uint32_t Offset) { 4441 IdentID ID = IdentifierIDs[II]; 4442 // Only store offsets new to this AST file. Other identifier names are looked 4443 // up earlier in the chain and thus don't need an offset. 4444 if (ID >= FirstIdentID) 4445 IdentifierOffsets[ID - FirstIdentID] = Offset; 4446 } 4447 4448 /// Note that the selector Sel occurs at the given offset 4449 /// within the method pool/selector table. 4450 void ASTWriter::SetSelectorOffset(Selector Sel, uint32_t Offset) { 4451 unsigned ID = SelectorIDs[Sel]; 4452 assert(ID && "Unknown selector"); 4453 // Don't record offsets for selectors that are also available in a different 4454 // file. 4455 if (ID < FirstSelectorID) 4456 return; 4457 SelectorOffsets[ID - FirstSelectorID] = Offset; 4458 } 4459 4460 ASTWriter::ASTWriter(llvm::BitstreamWriter &Stream, 4461 SmallVectorImpl<char> &Buffer, 4462 InMemoryModuleCache &ModuleCache, 4463 ArrayRef<std::shared_ptr<ModuleFileExtension>> Extensions, 4464 bool IncludeTimestamps) 4465 : Stream(Stream), Buffer(Buffer), ModuleCache(ModuleCache), 4466 IncludeTimestamps(IncludeTimestamps) { 4467 for (const auto &Ext : Extensions) { 4468 if (auto Writer = Ext->createExtensionWriter(*this)) 4469 ModuleFileExtensionWriters.push_back(std::move(Writer)); 4470 } 4471 } 4472 4473 ASTWriter::~ASTWriter() = default; 4474 4475 const LangOptions &ASTWriter::getLangOpts() const { 4476 assert(WritingAST && "can't determine lang opts when not writing AST"); 4477 return Context->getLangOpts(); 4478 } 4479 4480 time_t ASTWriter::getTimestampForOutput(const FileEntry *E) const { 4481 return IncludeTimestamps ? E->getModificationTime() : 0; 4482 } 4483 4484 ASTFileSignature ASTWriter::WriteAST(Sema &SemaRef, 4485 const std::string &OutputFile, 4486 Module *WritingModule, StringRef isysroot, 4487 bool hasErrors, 4488 bool ShouldCacheASTInMemory) { 4489 WritingAST = true; 4490 4491 ASTHasCompilerErrors = hasErrors; 4492 4493 // Emit the file header. 4494 Stream.Emit((unsigned)'C', 8); 4495 Stream.Emit((unsigned)'P', 8); 4496 Stream.Emit((unsigned)'C', 8); 4497 Stream.Emit((unsigned)'H', 8); 4498 4499 WriteBlockInfoBlock(); 4500 4501 Context = &SemaRef.Context; 4502 PP = &SemaRef.PP; 4503 this->WritingModule = WritingModule; 4504 ASTFileSignature Signature = 4505 WriteASTCore(SemaRef, isysroot, OutputFile, WritingModule); 4506 Context = nullptr; 4507 PP = nullptr; 4508 this->WritingModule = nullptr; 4509 this->BaseDirectory.clear(); 4510 4511 WritingAST = false; 4512 if (ShouldCacheASTInMemory) { 4513 // Construct MemoryBuffer and update buffer manager. 4514 ModuleCache.addBuiltPCM(OutputFile, 4515 llvm::MemoryBuffer::getMemBufferCopy( 4516 StringRef(Buffer.begin(), Buffer.size()))); 4517 } 4518 return Signature; 4519 } 4520 4521 template<typename Vector> 4522 static void AddLazyVectorDecls(ASTWriter &Writer, Vector &Vec, 4523 ASTWriter::RecordData &Record) { 4524 for (typename Vector::iterator I = Vec.begin(nullptr, true), E = Vec.end(); 4525 I != E; ++I) { 4526 Writer.AddDeclRef(*I, Record); 4527 } 4528 } 4529 4530 ASTFileSignature ASTWriter::WriteASTCore(Sema &SemaRef, StringRef isysroot, 4531 const std::string &OutputFile, 4532 Module *WritingModule) { 4533 using namespace llvm; 4534 4535 bool isModule = WritingModule != nullptr; 4536 4537 // Make sure that the AST reader knows to finalize itself. 4538 if (Chain) 4539 Chain->finalizeForWriting(); 4540 4541 ASTContext &Context = SemaRef.Context; 4542 Preprocessor &PP = SemaRef.PP; 4543 4544 // Set up predefined declaration IDs. 4545 auto RegisterPredefDecl = [&] (Decl *D, PredefinedDeclIDs ID) { 4546 if (D) { 4547 assert(D->isCanonicalDecl() && "predefined decl is not canonical"); 4548 DeclIDs[D] = ID; 4549 } 4550 }; 4551 RegisterPredefDecl(Context.getTranslationUnitDecl(), 4552 PREDEF_DECL_TRANSLATION_UNIT_ID); 4553 RegisterPredefDecl(Context.ObjCIdDecl, PREDEF_DECL_OBJC_ID_ID); 4554 RegisterPredefDecl(Context.ObjCSelDecl, PREDEF_DECL_OBJC_SEL_ID); 4555 RegisterPredefDecl(Context.ObjCClassDecl, PREDEF_DECL_OBJC_CLASS_ID); 4556 RegisterPredefDecl(Context.ObjCProtocolClassDecl, 4557 PREDEF_DECL_OBJC_PROTOCOL_ID); 4558 RegisterPredefDecl(Context.Int128Decl, PREDEF_DECL_INT_128_ID); 4559 RegisterPredefDecl(Context.UInt128Decl, PREDEF_DECL_UNSIGNED_INT_128_ID); 4560 RegisterPredefDecl(Context.ObjCInstanceTypeDecl, 4561 PREDEF_DECL_OBJC_INSTANCETYPE_ID); 4562 RegisterPredefDecl(Context.BuiltinVaListDecl, PREDEF_DECL_BUILTIN_VA_LIST_ID); 4563 RegisterPredefDecl(Context.VaListTagDecl, PREDEF_DECL_VA_LIST_TAG); 4564 RegisterPredefDecl(Context.BuiltinMSVaListDecl, 4565 PREDEF_DECL_BUILTIN_MS_VA_LIST_ID); 4566 RegisterPredefDecl(Context.MSGuidTagDecl, 4567 PREDEF_DECL_BUILTIN_MS_GUID_ID); 4568 RegisterPredefDecl(Context.ExternCContext, PREDEF_DECL_EXTERN_C_CONTEXT_ID); 4569 RegisterPredefDecl(Context.MakeIntegerSeqDecl, 4570 PREDEF_DECL_MAKE_INTEGER_SEQ_ID); 4571 RegisterPredefDecl(Context.CFConstantStringTypeDecl, 4572 PREDEF_DECL_CF_CONSTANT_STRING_ID); 4573 RegisterPredefDecl(Context.CFConstantStringTagDecl, 4574 PREDEF_DECL_CF_CONSTANT_STRING_TAG_ID); 4575 RegisterPredefDecl(Context.TypePackElementDecl, 4576 PREDEF_DECL_TYPE_PACK_ELEMENT_ID); 4577 4578 // Build a record containing all of the tentative definitions in this file, in 4579 // TentativeDefinitions order. Generally, this record will be empty for 4580 // headers. 4581 RecordData TentativeDefinitions; 4582 AddLazyVectorDecls(*this, SemaRef.TentativeDefinitions, TentativeDefinitions); 4583 4584 // Build a record containing all of the file scoped decls in this file. 4585 RecordData UnusedFileScopedDecls; 4586 if (!isModule) 4587 AddLazyVectorDecls(*this, SemaRef.UnusedFileScopedDecls, 4588 UnusedFileScopedDecls); 4589 4590 // Build a record containing all of the delegating constructors we still need 4591 // to resolve. 4592 RecordData DelegatingCtorDecls; 4593 if (!isModule) 4594 AddLazyVectorDecls(*this, SemaRef.DelegatingCtorDecls, DelegatingCtorDecls); 4595 4596 // Write the set of weak, undeclared identifiers. We always write the 4597 // entire table, since later PCH files in a PCH chain are only interested in 4598 // the results at the end of the chain. 4599 RecordData WeakUndeclaredIdentifiers; 4600 for (const auto &WeakUndeclaredIdentifierList : 4601 SemaRef.WeakUndeclaredIdentifiers) { 4602 const IdentifierInfo *const II = WeakUndeclaredIdentifierList.first; 4603 for (const auto &WI : WeakUndeclaredIdentifierList.second) { 4604 AddIdentifierRef(II, WeakUndeclaredIdentifiers); 4605 AddIdentifierRef(WI.getAlias(), WeakUndeclaredIdentifiers); 4606 AddSourceLocation(WI.getLocation(), WeakUndeclaredIdentifiers); 4607 } 4608 } 4609 4610 // Build a record containing all of the ext_vector declarations. 4611 RecordData ExtVectorDecls; 4612 AddLazyVectorDecls(*this, SemaRef.ExtVectorDecls, ExtVectorDecls); 4613 4614 // Build a record containing all of the VTable uses information. 4615 RecordData VTableUses; 4616 if (!SemaRef.VTableUses.empty()) { 4617 for (unsigned I = 0, N = SemaRef.VTableUses.size(); I != N; ++I) { 4618 AddDeclRef(SemaRef.VTableUses[I].first, VTableUses); 4619 AddSourceLocation(SemaRef.VTableUses[I].second, VTableUses); 4620 VTableUses.push_back(SemaRef.VTablesUsed[SemaRef.VTableUses[I].first]); 4621 } 4622 } 4623 4624 // Build a record containing all of the UnusedLocalTypedefNameCandidates. 4625 RecordData UnusedLocalTypedefNameCandidates; 4626 for (const TypedefNameDecl *TD : SemaRef.UnusedLocalTypedefNameCandidates) 4627 AddDeclRef(TD, UnusedLocalTypedefNameCandidates); 4628 4629 // Build a record containing all of pending implicit instantiations. 4630 RecordData PendingInstantiations; 4631 for (const auto &I : SemaRef.PendingInstantiations) { 4632 AddDeclRef(I.first, PendingInstantiations); 4633 AddSourceLocation(I.second, PendingInstantiations); 4634 } 4635 assert(SemaRef.PendingLocalImplicitInstantiations.empty() && 4636 "There are local ones at end of translation unit!"); 4637 4638 // Build a record containing some declaration references. 4639 RecordData SemaDeclRefs; 4640 if (SemaRef.StdNamespace || SemaRef.StdBadAlloc || SemaRef.StdAlignValT) { 4641 AddDeclRef(SemaRef.getStdNamespace(), SemaDeclRefs); 4642 AddDeclRef(SemaRef.getStdBadAlloc(), SemaDeclRefs); 4643 AddDeclRef(SemaRef.getStdAlignValT(), SemaDeclRefs); 4644 } 4645 4646 RecordData CUDASpecialDeclRefs; 4647 if (Context.getcudaConfigureCallDecl()) { 4648 AddDeclRef(Context.getcudaConfigureCallDecl(), CUDASpecialDeclRefs); 4649 } 4650 4651 // Build a record containing all of the known namespaces. 4652 RecordData KnownNamespaces; 4653 for (const auto &I : SemaRef.KnownNamespaces) { 4654 if (!I.second) 4655 AddDeclRef(I.first, KnownNamespaces); 4656 } 4657 4658 // Build a record of all used, undefined objects that require definitions. 4659 RecordData UndefinedButUsed; 4660 4661 SmallVector<std::pair<NamedDecl *, SourceLocation>, 16> Undefined; 4662 SemaRef.getUndefinedButUsed(Undefined); 4663 for (const auto &I : Undefined) { 4664 AddDeclRef(I.first, UndefinedButUsed); 4665 AddSourceLocation(I.second, UndefinedButUsed); 4666 } 4667 4668 // Build a record containing all delete-expressions that we would like to 4669 // analyze later in AST. 4670 RecordData DeleteExprsToAnalyze; 4671 4672 if (!isModule) { 4673 for (const auto &DeleteExprsInfo : 4674 SemaRef.getMismatchingDeleteExpressions()) { 4675 AddDeclRef(DeleteExprsInfo.first, DeleteExprsToAnalyze); 4676 DeleteExprsToAnalyze.push_back(DeleteExprsInfo.second.size()); 4677 for (const auto &DeleteLoc : DeleteExprsInfo.second) { 4678 AddSourceLocation(DeleteLoc.first, DeleteExprsToAnalyze); 4679 DeleteExprsToAnalyze.push_back(DeleteLoc.second); 4680 } 4681 } 4682 } 4683 4684 // Write the control block 4685 WriteControlBlock(PP, Context, isysroot, OutputFile); 4686 4687 // Write the remaining AST contents. 4688 Stream.FlushToWord(); 4689 ASTBlockRange.first = Stream.GetCurrentBitNo(); 4690 Stream.EnterSubblock(AST_BLOCK_ID, 5); 4691 ASTBlockStartOffset = Stream.GetCurrentBitNo(); 4692 4693 // This is so that older clang versions, before the introduction 4694 // of the control block, can read and reject the newer PCH format. 4695 { 4696 RecordData Record = {VERSION_MAJOR}; 4697 Stream.EmitRecord(METADATA_OLD_FORMAT, Record); 4698 } 4699 4700 // Create a lexical update block containing all of the declarations in the 4701 // translation unit that do not come from other AST files. 4702 const TranslationUnitDecl *TU = Context.getTranslationUnitDecl(); 4703 SmallVector<uint32_t, 128> NewGlobalKindDeclPairs; 4704 for (const auto *D : TU->noload_decls()) { 4705 if (!D->isFromASTFile()) { 4706 NewGlobalKindDeclPairs.push_back(D->getKind()); 4707 NewGlobalKindDeclPairs.push_back(GetDeclRef(D)); 4708 } 4709 } 4710 4711 auto Abv = std::make_shared<BitCodeAbbrev>(); 4712 Abv->Add(llvm::BitCodeAbbrevOp(TU_UPDATE_LEXICAL)); 4713 Abv->Add(llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::Blob)); 4714 unsigned TuUpdateLexicalAbbrev = Stream.EmitAbbrev(std::move(Abv)); 4715 { 4716 RecordData::value_type Record[] = {TU_UPDATE_LEXICAL}; 4717 Stream.EmitRecordWithBlob(TuUpdateLexicalAbbrev, Record, 4718 bytes(NewGlobalKindDeclPairs)); 4719 } 4720 4721 // And a visible updates block for the translation unit. 4722 Abv = std::make_shared<BitCodeAbbrev>(); 4723 Abv->Add(llvm::BitCodeAbbrevOp(UPDATE_VISIBLE)); 4724 Abv->Add(llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::VBR, 6)); 4725 Abv->Add(llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::Blob)); 4726 UpdateVisibleAbbrev = Stream.EmitAbbrev(std::move(Abv)); 4727 WriteDeclContextVisibleUpdate(TU); 4728 4729 // If we have any extern "C" names, write out a visible update for them. 4730 if (Context.ExternCContext) 4731 WriteDeclContextVisibleUpdate(Context.ExternCContext); 4732 4733 // If the translation unit has an anonymous namespace, and we don't already 4734 // have an update block for it, write it as an update block. 4735 // FIXME: Why do we not do this if there's already an update block? 4736 if (NamespaceDecl *NS = TU->getAnonymousNamespace()) { 4737 ASTWriter::UpdateRecord &Record = DeclUpdates[TU]; 4738 if (Record.empty()) 4739 Record.push_back(DeclUpdate(UPD_CXX_ADDED_ANONYMOUS_NAMESPACE, NS)); 4740 } 4741 4742 // Add update records for all mangling numbers and static local numbers. 4743 // These aren't really update records, but this is a convenient way of 4744 // tagging this rare extra data onto the declarations. 4745 for (const auto &Number : Context.MangleNumbers) 4746 if (!Number.first->isFromASTFile()) 4747 DeclUpdates[Number.first].push_back(DeclUpdate(UPD_MANGLING_NUMBER, 4748 Number.second)); 4749 for (const auto &Number : Context.StaticLocalNumbers) 4750 if (!Number.first->isFromASTFile()) 4751 DeclUpdates[Number.first].push_back(DeclUpdate(UPD_STATIC_LOCAL_NUMBER, 4752 Number.second)); 4753 4754 // Make sure visible decls, added to DeclContexts previously loaded from 4755 // an AST file, are registered for serialization. Likewise for template 4756 // specializations added to imported templates. 4757 for (const auto *I : DeclsToEmitEvenIfUnreferenced) { 4758 GetDeclRef(I); 4759 } 4760 4761 // Make sure all decls associated with an identifier are registered for 4762 // serialization, if we're storing decls with identifiers. 4763 if (!WritingModule || !getLangOpts().CPlusPlus) { 4764 llvm::SmallVector<const IdentifierInfo*, 256> IIs; 4765 for (const auto &ID : PP.getIdentifierTable()) { 4766 const IdentifierInfo *II = ID.second; 4767 if (!Chain || !II->isFromAST() || II->hasChangedSinceDeserialization()) 4768 IIs.push_back(II); 4769 } 4770 // Sort the identifiers to visit based on their name. 4771 llvm::sort(IIs, llvm::deref<std::less<>>()); 4772 for (const IdentifierInfo *II : IIs) { 4773 for (IdentifierResolver::iterator D = SemaRef.IdResolver.begin(II), 4774 DEnd = SemaRef.IdResolver.end(); 4775 D != DEnd; ++D) { 4776 GetDeclRef(*D); 4777 } 4778 } 4779 } 4780 4781 // For method pool in the module, if it contains an entry for a selector, 4782 // the entry should be complete, containing everything introduced by that 4783 // module and all modules it imports. It's possible that the entry is out of 4784 // date, so we need to pull in the new content here. 4785 4786 // It's possible that updateOutOfDateSelector can update SelectorIDs. To be 4787 // safe, we copy all selectors out. 4788 llvm::SmallVector<Selector, 256> AllSelectors; 4789 for (auto &SelectorAndID : SelectorIDs) 4790 AllSelectors.push_back(SelectorAndID.first); 4791 for (auto &Selector : AllSelectors) 4792 SemaRef.updateOutOfDateSelector(Selector); 4793 4794 // Form the record of special types. 4795 RecordData SpecialTypes; 4796 AddTypeRef(Context.getRawCFConstantStringType(), SpecialTypes); 4797 AddTypeRef(Context.getFILEType(), SpecialTypes); 4798 AddTypeRef(Context.getjmp_bufType(), SpecialTypes); 4799 AddTypeRef(Context.getsigjmp_bufType(), SpecialTypes); 4800 AddTypeRef(Context.ObjCIdRedefinitionType, SpecialTypes); 4801 AddTypeRef(Context.ObjCClassRedefinitionType, SpecialTypes); 4802 AddTypeRef(Context.ObjCSelRedefinitionType, SpecialTypes); 4803 AddTypeRef(Context.getucontext_tType(), SpecialTypes); 4804 4805 if (Chain) { 4806 // Write the mapping information describing our module dependencies and how 4807 // each of those modules were mapped into our own offset/ID space, so that 4808 // the reader can build the appropriate mapping to its own offset/ID space. 4809 // The map consists solely of a blob with the following format: 4810 // *(module-kind:i8 4811 // module-name-len:i16 module-name:len*i8 4812 // source-location-offset:i32 4813 // identifier-id:i32 4814 // preprocessed-entity-id:i32 4815 // macro-definition-id:i32 4816 // submodule-id:i32 4817 // selector-id:i32 4818 // declaration-id:i32 4819 // c++-base-specifiers-id:i32 4820 // type-id:i32) 4821 // 4822 // module-kind is the ModuleKind enum value. If it is MK_PrebuiltModule, 4823 // MK_ExplicitModule or MK_ImplicitModule, then the module-name is the 4824 // module name. Otherwise, it is the module file name. 4825 auto Abbrev = std::make_shared<BitCodeAbbrev>(); 4826 Abbrev->Add(BitCodeAbbrevOp(MODULE_OFFSET_MAP)); 4827 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); 4828 unsigned ModuleOffsetMapAbbrev = Stream.EmitAbbrev(std::move(Abbrev)); 4829 SmallString<2048> Buffer; 4830 { 4831 llvm::raw_svector_ostream Out(Buffer); 4832 for (ModuleFile &M : Chain->ModuleMgr) { 4833 using namespace llvm::support; 4834 4835 endian::Writer LE(Out, little); 4836 LE.write<uint8_t>(static_cast<uint8_t>(M.Kind)); 4837 StringRef Name = M.isModule() ? M.ModuleName : M.FileName; 4838 LE.write<uint16_t>(Name.size()); 4839 Out.write(Name.data(), Name.size()); 4840 4841 // Note: if a base ID was uint max, it would not be possible to load 4842 // another module after it or have more than one entity inside it. 4843 uint32_t None = std::numeric_limits<uint32_t>::max(); 4844 4845 auto writeBaseIDOrNone = [&](auto BaseID, bool ShouldWrite) { 4846 assert(BaseID < std::numeric_limits<uint32_t>::max() && "base id too high"); 4847 if (ShouldWrite) 4848 LE.write<uint32_t>(BaseID); 4849 else 4850 LE.write<uint32_t>(None); 4851 }; 4852 4853 // These values should be unique within a chain, since they will be read 4854 // as keys into ContinuousRangeMaps. 4855 writeBaseIDOrNone(M.SLocEntryBaseOffset, M.LocalNumSLocEntries); 4856 writeBaseIDOrNone(M.BaseIdentifierID, M.LocalNumIdentifiers); 4857 writeBaseIDOrNone(M.BaseMacroID, M.LocalNumMacros); 4858 writeBaseIDOrNone(M.BasePreprocessedEntityID, 4859 M.NumPreprocessedEntities); 4860 writeBaseIDOrNone(M.BaseSubmoduleID, M.LocalNumSubmodules); 4861 writeBaseIDOrNone(M.BaseSelectorID, M.LocalNumSelectors); 4862 writeBaseIDOrNone(M.BaseDeclID, M.LocalNumDecls); 4863 writeBaseIDOrNone(M.BaseTypeIndex, M.LocalNumTypes); 4864 } 4865 } 4866 RecordData::value_type Record[] = {MODULE_OFFSET_MAP}; 4867 Stream.EmitRecordWithBlob(ModuleOffsetMapAbbrev, Record, 4868 Buffer.data(), Buffer.size()); 4869 } 4870 4871 // Build a record containing all of the DeclsToCheckForDeferredDiags. 4872 SmallVector<serialization::DeclID, 64> DeclsToCheckForDeferredDiags; 4873 for (auto *D : SemaRef.DeclsToCheckForDeferredDiags) 4874 DeclsToCheckForDeferredDiags.push_back(GetDeclRef(D)); 4875 4876 RecordData DeclUpdatesOffsetsRecord; 4877 4878 // Keep writing types, declarations, and declaration update records 4879 // until we've emitted all of them. 4880 Stream.EnterSubblock(DECLTYPES_BLOCK_ID, /*bits for abbreviations*/5); 4881 DeclTypesBlockStartOffset = Stream.GetCurrentBitNo(); 4882 WriteTypeAbbrevs(); 4883 WriteDeclAbbrevs(); 4884 do { 4885 WriteDeclUpdatesBlocks(DeclUpdatesOffsetsRecord); 4886 while (!DeclTypesToEmit.empty()) { 4887 DeclOrType DOT = DeclTypesToEmit.front(); 4888 DeclTypesToEmit.pop(); 4889 if (DOT.isType()) 4890 WriteType(DOT.getType()); 4891 else 4892 WriteDecl(Context, DOT.getDecl()); 4893 } 4894 } while (!DeclUpdates.empty()); 4895 Stream.ExitBlock(); 4896 4897 DoneWritingDeclsAndTypes = true; 4898 4899 // These things can only be done once we've written out decls and types. 4900 WriteTypeDeclOffsets(); 4901 if (!DeclUpdatesOffsetsRecord.empty()) 4902 Stream.EmitRecord(DECL_UPDATE_OFFSETS, DeclUpdatesOffsetsRecord); 4903 WriteFileDeclIDsMap(); 4904 WriteSourceManagerBlock(Context.getSourceManager(), PP); 4905 WriteComments(); 4906 WritePreprocessor(PP, isModule); 4907 WriteHeaderSearch(PP.getHeaderSearchInfo()); 4908 WriteSelectors(SemaRef); 4909 WriteReferencedSelectorsPool(SemaRef); 4910 WriteLateParsedTemplates(SemaRef); 4911 WriteIdentifierTable(PP, SemaRef.IdResolver, isModule); 4912 WriteFPPragmaOptions(SemaRef.CurFPFeatureOverrides()); 4913 WriteOpenCLExtensions(SemaRef); 4914 WriteCUDAPragmas(SemaRef); 4915 4916 // If we're emitting a module, write out the submodule information. 4917 if (WritingModule) 4918 WriteSubmodules(WritingModule); 4919 4920 Stream.EmitRecord(SPECIAL_TYPES, SpecialTypes); 4921 4922 // Write the record containing external, unnamed definitions. 4923 if (!EagerlyDeserializedDecls.empty()) 4924 Stream.EmitRecord(EAGERLY_DESERIALIZED_DECLS, EagerlyDeserializedDecls); 4925 4926 if (!ModularCodegenDecls.empty()) 4927 Stream.EmitRecord(MODULAR_CODEGEN_DECLS, ModularCodegenDecls); 4928 4929 // Write the record containing tentative definitions. 4930 if (!TentativeDefinitions.empty()) 4931 Stream.EmitRecord(TENTATIVE_DEFINITIONS, TentativeDefinitions); 4932 4933 // Write the record containing unused file scoped decls. 4934 if (!UnusedFileScopedDecls.empty()) 4935 Stream.EmitRecord(UNUSED_FILESCOPED_DECLS, UnusedFileScopedDecls); 4936 4937 // Write the record containing weak undeclared identifiers. 4938 if (!WeakUndeclaredIdentifiers.empty()) 4939 Stream.EmitRecord(WEAK_UNDECLARED_IDENTIFIERS, 4940 WeakUndeclaredIdentifiers); 4941 4942 // Write the record containing ext_vector type names. 4943 if (!ExtVectorDecls.empty()) 4944 Stream.EmitRecord(EXT_VECTOR_DECLS, ExtVectorDecls); 4945 4946 // Write the record containing VTable uses information. 4947 if (!VTableUses.empty()) 4948 Stream.EmitRecord(VTABLE_USES, VTableUses); 4949 4950 // Write the record containing potentially unused local typedefs. 4951 if (!UnusedLocalTypedefNameCandidates.empty()) 4952 Stream.EmitRecord(UNUSED_LOCAL_TYPEDEF_NAME_CANDIDATES, 4953 UnusedLocalTypedefNameCandidates); 4954 4955 // Write the record containing pending implicit instantiations. 4956 if (!PendingInstantiations.empty()) 4957 Stream.EmitRecord(PENDING_IMPLICIT_INSTANTIATIONS, PendingInstantiations); 4958 4959 // Write the record containing declaration references of Sema. 4960 if (!SemaDeclRefs.empty()) 4961 Stream.EmitRecord(SEMA_DECL_REFS, SemaDeclRefs); 4962 4963 // Write the record containing decls to be checked for deferred diags. 4964 if (!DeclsToCheckForDeferredDiags.empty()) 4965 Stream.EmitRecord(DECLS_TO_CHECK_FOR_DEFERRED_DIAGS, 4966 DeclsToCheckForDeferredDiags); 4967 4968 // Write the record containing CUDA-specific declaration references. 4969 if (!CUDASpecialDeclRefs.empty()) 4970 Stream.EmitRecord(CUDA_SPECIAL_DECL_REFS, CUDASpecialDeclRefs); 4971 4972 // Write the delegating constructors. 4973 if (!DelegatingCtorDecls.empty()) 4974 Stream.EmitRecord(DELEGATING_CTORS, DelegatingCtorDecls); 4975 4976 // Write the known namespaces. 4977 if (!KnownNamespaces.empty()) 4978 Stream.EmitRecord(KNOWN_NAMESPACES, KnownNamespaces); 4979 4980 // Write the undefined internal functions and variables, and inline functions. 4981 if (!UndefinedButUsed.empty()) 4982 Stream.EmitRecord(UNDEFINED_BUT_USED, UndefinedButUsed); 4983 4984 if (!DeleteExprsToAnalyze.empty()) 4985 Stream.EmitRecord(DELETE_EXPRS_TO_ANALYZE, DeleteExprsToAnalyze); 4986 4987 // Write the visible updates to DeclContexts. 4988 for (auto *DC : UpdatedDeclContexts) 4989 WriteDeclContextVisibleUpdate(DC); 4990 4991 if (!WritingModule) { 4992 // Write the submodules that were imported, if any. 4993 struct ModuleInfo { 4994 uint64_t ID; 4995 Module *M; 4996 ModuleInfo(uint64_t ID, Module *M) : ID(ID), M(M) {} 4997 }; 4998 llvm::SmallVector<ModuleInfo, 64> Imports; 4999 for (const auto *I : Context.local_imports()) { 5000 assert(SubmoduleIDs.find(I->getImportedModule()) != SubmoduleIDs.end()); 5001 Imports.push_back(ModuleInfo(SubmoduleIDs[I->getImportedModule()], 5002 I->getImportedModule())); 5003 } 5004 5005 if (!Imports.empty()) { 5006 auto Cmp = [](const ModuleInfo &A, const ModuleInfo &B) { 5007 return A.ID < B.ID; 5008 }; 5009 auto Eq = [](const ModuleInfo &A, const ModuleInfo &B) { 5010 return A.ID == B.ID; 5011 }; 5012 5013 // Sort and deduplicate module IDs. 5014 llvm::sort(Imports, Cmp); 5015 Imports.erase(std::unique(Imports.begin(), Imports.end(), Eq), 5016 Imports.end()); 5017 5018 RecordData ImportedModules; 5019 for (const auto &Import : Imports) { 5020 ImportedModules.push_back(Import.ID); 5021 // FIXME: If the module has macros imported then later has declarations 5022 // imported, this location won't be the right one as a location for the 5023 // declaration imports. 5024 AddSourceLocation(PP.getModuleImportLoc(Import.M), ImportedModules); 5025 } 5026 5027 Stream.EmitRecord(IMPORTED_MODULES, ImportedModules); 5028 } 5029 } 5030 5031 WriteObjCCategories(); 5032 if(!WritingModule) { 5033 WriteOptimizePragmaOptions(SemaRef); 5034 WriteMSStructPragmaOptions(SemaRef); 5035 WriteMSPointersToMembersPragmaOptions(SemaRef); 5036 } 5037 WritePackPragmaOptions(SemaRef); 5038 WriteFloatControlPragmaOptions(SemaRef); 5039 5040 // Some simple statistics 5041 RecordData::value_type Record[] = { 5042 NumStatements, NumMacros, NumLexicalDeclContexts, NumVisibleDeclContexts}; 5043 Stream.EmitRecord(STATISTICS, Record); 5044 Stream.ExitBlock(); 5045 Stream.FlushToWord(); 5046 ASTBlockRange.second = Stream.GetCurrentBitNo(); 5047 5048 // Write the module file extension blocks. 5049 for (const auto &ExtWriter : ModuleFileExtensionWriters) 5050 WriteModuleFileExtension(SemaRef, *ExtWriter); 5051 5052 return writeUnhashedControlBlock(PP, Context); 5053 } 5054 5055 void ASTWriter::WriteDeclUpdatesBlocks(RecordDataImpl &OffsetsRecord) { 5056 if (DeclUpdates.empty()) 5057 return; 5058 5059 DeclUpdateMap LocalUpdates; 5060 LocalUpdates.swap(DeclUpdates); 5061 5062 for (auto &DeclUpdate : LocalUpdates) { 5063 const Decl *D = DeclUpdate.first; 5064 5065 bool HasUpdatedBody = false; 5066 RecordData RecordData; 5067 ASTRecordWriter Record(*this, RecordData); 5068 for (auto &Update : DeclUpdate.second) { 5069 DeclUpdateKind Kind = (DeclUpdateKind)Update.getKind(); 5070 5071 // An updated body is emitted last, so that the reader doesn't need 5072 // to skip over the lazy body to reach statements for other records. 5073 if (Kind == UPD_CXX_ADDED_FUNCTION_DEFINITION) 5074 HasUpdatedBody = true; 5075 else 5076 Record.push_back(Kind); 5077 5078 switch (Kind) { 5079 case UPD_CXX_ADDED_IMPLICIT_MEMBER: 5080 case UPD_CXX_ADDED_TEMPLATE_SPECIALIZATION: 5081 case UPD_CXX_ADDED_ANONYMOUS_NAMESPACE: 5082 assert(Update.getDecl() && "no decl to add?"); 5083 Record.push_back(GetDeclRef(Update.getDecl())); 5084 break; 5085 5086 case UPD_CXX_ADDED_FUNCTION_DEFINITION: 5087 break; 5088 5089 case UPD_CXX_POINT_OF_INSTANTIATION: 5090 // FIXME: Do we need to also save the template specialization kind here? 5091 Record.AddSourceLocation(Update.getLoc()); 5092 break; 5093 5094 case UPD_CXX_ADDED_VAR_DEFINITION: { 5095 const VarDecl *VD = cast<VarDecl>(D); 5096 Record.push_back(VD->isInline()); 5097 Record.push_back(VD->isInlineSpecified()); 5098 Record.AddVarDeclInit(VD); 5099 break; 5100 } 5101 5102 case UPD_CXX_INSTANTIATED_DEFAULT_ARGUMENT: 5103 Record.AddStmt(const_cast<Expr *>( 5104 cast<ParmVarDecl>(Update.getDecl())->getDefaultArg())); 5105 break; 5106 5107 case UPD_CXX_INSTANTIATED_DEFAULT_MEMBER_INITIALIZER: 5108 Record.AddStmt( 5109 cast<FieldDecl>(Update.getDecl())->getInClassInitializer()); 5110 break; 5111 5112 case UPD_CXX_INSTANTIATED_CLASS_DEFINITION: { 5113 auto *RD = cast<CXXRecordDecl>(D); 5114 UpdatedDeclContexts.insert(RD->getPrimaryContext()); 5115 Record.push_back(RD->isParamDestroyedInCallee()); 5116 Record.push_back(RD->getArgPassingRestrictions()); 5117 Record.AddCXXDefinitionData(RD); 5118 Record.AddOffset(WriteDeclContextLexicalBlock( 5119 *Context, const_cast<CXXRecordDecl *>(RD))); 5120 5121 // This state is sometimes updated by template instantiation, when we 5122 // switch from the specialization referring to the template declaration 5123 // to it referring to the template definition. 5124 if (auto *MSInfo = RD->getMemberSpecializationInfo()) { 5125 Record.push_back(MSInfo->getTemplateSpecializationKind()); 5126 Record.AddSourceLocation(MSInfo->getPointOfInstantiation()); 5127 } else { 5128 auto *Spec = cast<ClassTemplateSpecializationDecl>(RD); 5129 Record.push_back(Spec->getTemplateSpecializationKind()); 5130 Record.AddSourceLocation(Spec->getPointOfInstantiation()); 5131 5132 // The instantiation might have been resolved to a partial 5133 // specialization. If so, record which one. 5134 auto From = Spec->getInstantiatedFrom(); 5135 if (auto PartialSpec = 5136 From.dyn_cast<ClassTemplatePartialSpecializationDecl*>()) { 5137 Record.push_back(true); 5138 Record.AddDeclRef(PartialSpec); 5139 Record.AddTemplateArgumentList( 5140 &Spec->getTemplateInstantiationArgs()); 5141 } else { 5142 Record.push_back(false); 5143 } 5144 } 5145 Record.push_back(RD->getTagKind()); 5146 Record.AddSourceLocation(RD->getLocation()); 5147 Record.AddSourceLocation(RD->getBeginLoc()); 5148 Record.AddSourceRange(RD->getBraceRange()); 5149 5150 // Instantiation may change attributes; write them all out afresh. 5151 Record.push_back(D->hasAttrs()); 5152 if (D->hasAttrs()) 5153 Record.AddAttributes(D->getAttrs()); 5154 5155 // FIXME: Ensure we don't get here for explicit instantiations. 5156 break; 5157 } 5158 5159 case UPD_CXX_RESOLVED_DTOR_DELETE: 5160 Record.AddDeclRef(Update.getDecl()); 5161 Record.AddStmt(cast<CXXDestructorDecl>(D)->getOperatorDeleteThisArg()); 5162 break; 5163 5164 case UPD_CXX_RESOLVED_EXCEPTION_SPEC: { 5165 auto prototype = 5166 cast<FunctionDecl>(D)->getType()->castAs<FunctionProtoType>(); 5167 Record.writeExceptionSpecInfo(prototype->getExceptionSpecInfo()); 5168 break; 5169 } 5170 5171 case UPD_CXX_DEDUCED_RETURN_TYPE: 5172 Record.push_back(GetOrCreateTypeID(Update.getType())); 5173 break; 5174 5175 case UPD_DECL_MARKED_USED: 5176 break; 5177 5178 case UPD_MANGLING_NUMBER: 5179 case UPD_STATIC_LOCAL_NUMBER: 5180 Record.push_back(Update.getNumber()); 5181 break; 5182 5183 case UPD_DECL_MARKED_OPENMP_THREADPRIVATE: 5184 Record.AddSourceRange( 5185 D->getAttr<OMPThreadPrivateDeclAttr>()->getRange()); 5186 break; 5187 5188 case UPD_DECL_MARKED_OPENMP_ALLOCATE: { 5189 auto *A = D->getAttr<OMPAllocateDeclAttr>(); 5190 Record.push_back(A->getAllocatorType()); 5191 Record.AddStmt(A->getAllocator()); 5192 Record.AddStmt(A->getAlignment()); 5193 Record.AddSourceRange(A->getRange()); 5194 break; 5195 } 5196 5197 case UPD_DECL_MARKED_OPENMP_DECLARETARGET: 5198 Record.push_back(D->getAttr<OMPDeclareTargetDeclAttr>()->getMapType()); 5199 Record.AddSourceRange( 5200 D->getAttr<OMPDeclareTargetDeclAttr>()->getRange()); 5201 break; 5202 5203 case UPD_DECL_EXPORTED: 5204 Record.push_back(getSubmoduleID(Update.getModule())); 5205 break; 5206 5207 case UPD_ADDED_ATTR_TO_RECORD: 5208 Record.AddAttributes(llvm::makeArrayRef(Update.getAttr())); 5209 break; 5210 } 5211 } 5212 5213 if (HasUpdatedBody) { 5214 const auto *Def = cast<FunctionDecl>(D); 5215 Record.push_back(UPD_CXX_ADDED_FUNCTION_DEFINITION); 5216 Record.push_back(Def->isInlined()); 5217 Record.AddSourceLocation(Def->getInnerLocStart()); 5218 Record.AddFunctionDefinition(Def); 5219 } 5220 5221 OffsetsRecord.push_back(GetDeclRef(D)); 5222 OffsetsRecord.push_back(Record.Emit(DECL_UPDATES)); 5223 } 5224 } 5225 5226 void ASTWriter::AddAlignPackInfo(const Sema::AlignPackInfo &Info, 5227 RecordDataImpl &Record) { 5228 uint32_t Raw = Sema::AlignPackInfo::getRawEncoding(Info); 5229 Record.push_back(Raw); 5230 } 5231 5232 void ASTWriter::AddSourceLocation(SourceLocation Loc, RecordDataImpl &Record, 5233 SourceLocationSequence *Seq) { 5234 Record.push_back(SourceLocationEncoding::encode(Loc, Seq)); 5235 } 5236 5237 void ASTWriter::AddSourceRange(SourceRange Range, RecordDataImpl &Record, 5238 SourceLocationSequence *Seq) { 5239 AddSourceLocation(Range.getBegin(), Record, Seq); 5240 AddSourceLocation(Range.getEnd(), Record, Seq); 5241 } 5242 5243 void ASTRecordWriter::AddAPFloat(const llvm::APFloat &Value) { 5244 AddAPInt(Value.bitcastToAPInt()); 5245 } 5246 5247 void ASTWriter::AddIdentifierRef(const IdentifierInfo *II, RecordDataImpl &Record) { 5248 Record.push_back(getIdentifierRef(II)); 5249 } 5250 5251 IdentID ASTWriter::getIdentifierRef(const IdentifierInfo *II) { 5252 if (!II) 5253 return 0; 5254 5255 IdentID &ID = IdentifierIDs[II]; 5256 if (ID == 0) 5257 ID = NextIdentID++; 5258 return ID; 5259 } 5260 5261 MacroID ASTWriter::getMacroRef(MacroInfo *MI, const IdentifierInfo *Name) { 5262 // Don't emit builtin macros like __LINE__ to the AST file unless they 5263 // have been redefined by the header (in which case they are not 5264 // isBuiltinMacro). 5265 if (!MI || MI->isBuiltinMacro()) 5266 return 0; 5267 5268 MacroID &ID = MacroIDs[MI]; 5269 if (ID == 0) { 5270 ID = NextMacroID++; 5271 MacroInfoToEmitData Info = { Name, MI, ID }; 5272 MacroInfosToEmit.push_back(Info); 5273 } 5274 return ID; 5275 } 5276 5277 MacroID ASTWriter::getMacroID(MacroInfo *MI) { 5278 if (!MI || MI->isBuiltinMacro()) 5279 return 0; 5280 5281 assert(MacroIDs.find(MI) != MacroIDs.end() && "Macro not emitted!"); 5282 return MacroIDs[MI]; 5283 } 5284 5285 uint32_t ASTWriter::getMacroDirectivesOffset(const IdentifierInfo *Name) { 5286 return IdentMacroDirectivesOffsetMap.lookup(Name); 5287 } 5288 5289 void ASTRecordWriter::AddSelectorRef(const Selector SelRef) { 5290 Record->push_back(Writer->getSelectorRef(SelRef)); 5291 } 5292 5293 SelectorID ASTWriter::getSelectorRef(Selector Sel) { 5294 if (Sel.getAsOpaquePtr() == nullptr) { 5295 return 0; 5296 } 5297 5298 SelectorID SID = SelectorIDs[Sel]; 5299 if (SID == 0 && Chain) { 5300 // This might trigger a ReadSelector callback, which will set the ID for 5301 // this selector. 5302 Chain->LoadSelector(Sel); 5303 SID = SelectorIDs[Sel]; 5304 } 5305 if (SID == 0) { 5306 SID = NextSelectorID++; 5307 SelectorIDs[Sel] = SID; 5308 } 5309 return SID; 5310 } 5311 5312 void ASTRecordWriter::AddCXXTemporary(const CXXTemporary *Temp) { 5313 AddDeclRef(Temp->getDestructor()); 5314 } 5315 5316 void ASTRecordWriter::AddTemplateArgumentLocInfo( 5317 TemplateArgument::ArgKind Kind, const TemplateArgumentLocInfo &Arg) { 5318 switch (Kind) { 5319 case TemplateArgument::Expression: 5320 AddStmt(Arg.getAsExpr()); 5321 break; 5322 case TemplateArgument::Type: 5323 AddTypeSourceInfo(Arg.getAsTypeSourceInfo()); 5324 break; 5325 case TemplateArgument::Template: 5326 AddNestedNameSpecifierLoc(Arg.getTemplateQualifierLoc()); 5327 AddSourceLocation(Arg.getTemplateNameLoc()); 5328 break; 5329 case TemplateArgument::TemplateExpansion: 5330 AddNestedNameSpecifierLoc(Arg.getTemplateQualifierLoc()); 5331 AddSourceLocation(Arg.getTemplateNameLoc()); 5332 AddSourceLocation(Arg.getTemplateEllipsisLoc()); 5333 break; 5334 case TemplateArgument::Null: 5335 case TemplateArgument::Integral: 5336 case TemplateArgument::Declaration: 5337 case TemplateArgument::NullPtr: 5338 case TemplateArgument::Pack: 5339 // FIXME: Is this right? 5340 break; 5341 } 5342 } 5343 5344 void ASTRecordWriter::AddTemplateArgumentLoc(const TemplateArgumentLoc &Arg) { 5345 AddTemplateArgument(Arg.getArgument()); 5346 5347 if (Arg.getArgument().getKind() == TemplateArgument::Expression) { 5348 bool InfoHasSameExpr 5349 = Arg.getArgument().getAsExpr() == Arg.getLocInfo().getAsExpr(); 5350 Record->push_back(InfoHasSameExpr); 5351 if (InfoHasSameExpr) 5352 return; // Avoid storing the same expr twice. 5353 } 5354 AddTemplateArgumentLocInfo(Arg.getArgument().getKind(), Arg.getLocInfo()); 5355 } 5356 5357 void ASTRecordWriter::AddTypeSourceInfo(TypeSourceInfo *TInfo) { 5358 if (!TInfo) { 5359 AddTypeRef(QualType()); 5360 return; 5361 } 5362 5363 AddTypeRef(TInfo->getType()); 5364 AddTypeLoc(TInfo->getTypeLoc()); 5365 } 5366 5367 void ASTRecordWriter::AddTypeLoc(TypeLoc TL, LocSeq *OuterSeq) { 5368 LocSeq::State Seq(OuterSeq); 5369 TypeLocWriter TLW(*this, Seq); 5370 for (; !TL.isNull(); TL = TL.getNextTypeLoc()) 5371 TLW.Visit(TL); 5372 } 5373 5374 void ASTWriter::AddTypeRef(QualType T, RecordDataImpl &Record) { 5375 Record.push_back(GetOrCreateTypeID(T)); 5376 } 5377 5378 TypeID ASTWriter::GetOrCreateTypeID(QualType T) { 5379 assert(Context); 5380 return MakeTypeID(*Context, T, [&](QualType T) -> TypeIdx { 5381 if (T.isNull()) 5382 return TypeIdx(); 5383 assert(!T.getLocalFastQualifiers()); 5384 5385 TypeIdx &Idx = TypeIdxs[T]; 5386 if (Idx.getIndex() == 0) { 5387 if (DoneWritingDeclsAndTypes) { 5388 assert(0 && "New type seen after serializing all the types to emit!"); 5389 return TypeIdx(); 5390 } 5391 5392 // We haven't seen this type before. Assign it a new ID and put it 5393 // into the queue of types to emit. 5394 Idx = TypeIdx(NextTypeID++); 5395 DeclTypesToEmit.push(T); 5396 } 5397 return Idx; 5398 }); 5399 } 5400 5401 TypeID ASTWriter::getTypeID(QualType T) const { 5402 assert(Context); 5403 return MakeTypeID(*Context, T, [&](QualType T) -> TypeIdx { 5404 if (T.isNull()) 5405 return TypeIdx(); 5406 assert(!T.getLocalFastQualifiers()); 5407 5408 TypeIdxMap::const_iterator I = TypeIdxs.find(T); 5409 assert(I != TypeIdxs.end() && "Type not emitted!"); 5410 return I->second; 5411 }); 5412 } 5413 5414 void ASTWriter::AddDeclRef(const Decl *D, RecordDataImpl &Record) { 5415 Record.push_back(GetDeclRef(D)); 5416 } 5417 5418 DeclID ASTWriter::GetDeclRef(const Decl *D) { 5419 assert(WritingAST && "Cannot request a declaration ID before AST writing"); 5420 5421 if (!D) { 5422 return 0; 5423 } 5424 5425 // If D comes from an AST file, its declaration ID is already known and 5426 // fixed. 5427 if (D->isFromASTFile()) 5428 return D->getGlobalID(); 5429 5430 assert(!(reinterpret_cast<uintptr_t>(D) & 0x01) && "Invalid decl pointer"); 5431 DeclID &ID = DeclIDs[D]; 5432 if (ID == 0) { 5433 if (DoneWritingDeclsAndTypes) { 5434 assert(0 && "New decl seen after serializing all the decls to emit!"); 5435 return 0; 5436 } 5437 5438 // We haven't seen this declaration before. Give it a new ID and 5439 // enqueue it in the list of declarations to emit. 5440 ID = NextDeclID++; 5441 DeclTypesToEmit.push(const_cast<Decl *>(D)); 5442 } 5443 5444 return ID; 5445 } 5446 5447 DeclID ASTWriter::getDeclID(const Decl *D) { 5448 if (!D) 5449 return 0; 5450 5451 // If D comes from an AST file, its declaration ID is already known and 5452 // fixed. 5453 if (D->isFromASTFile()) 5454 return D->getGlobalID(); 5455 5456 assert(DeclIDs.find(D) != DeclIDs.end() && "Declaration not emitted!"); 5457 return DeclIDs[D]; 5458 } 5459 5460 void ASTWriter::associateDeclWithFile(const Decl *D, DeclID ID) { 5461 assert(ID); 5462 assert(D); 5463 5464 SourceLocation Loc = D->getLocation(); 5465 if (Loc.isInvalid()) 5466 return; 5467 5468 // We only keep track of the file-level declarations of each file. 5469 if (!D->getLexicalDeclContext()->isFileContext()) 5470 return; 5471 // FIXME: ParmVarDecls that are part of a function type of a parameter of 5472 // a function/objc method, should not have TU as lexical context. 5473 // TemplateTemplateParmDecls that are part of an alias template, should not 5474 // have TU as lexical context. 5475 if (isa<ParmVarDecl>(D) || isa<TemplateTemplateParmDecl>(D)) 5476 return; 5477 5478 SourceManager &SM = Context->getSourceManager(); 5479 SourceLocation FileLoc = SM.getFileLoc(Loc); 5480 assert(SM.isLocalSourceLocation(FileLoc)); 5481 FileID FID; 5482 unsigned Offset; 5483 std::tie(FID, Offset) = SM.getDecomposedLoc(FileLoc); 5484 if (FID.isInvalid()) 5485 return; 5486 assert(SM.getSLocEntry(FID).isFile()); 5487 5488 std::unique_ptr<DeclIDInFileInfo> &Info = FileDeclIDs[FID]; 5489 if (!Info) 5490 Info = std::make_unique<DeclIDInFileInfo>(); 5491 5492 std::pair<unsigned, serialization::DeclID> LocDecl(Offset, ID); 5493 LocDeclIDsTy &Decls = Info->DeclIDs; 5494 Decls.push_back(LocDecl); 5495 } 5496 5497 unsigned ASTWriter::getAnonymousDeclarationNumber(const NamedDecl *D) { 5498 assert(needsAnonymousDeclarationNumber(D) && 5499 "expected an anonymous declaration"); 5500 5501 // Number the anonymous declarations within this context, if we've not 5502 // already done so. 5503 auto It = AnonymousDeclarationNumbers.find(D); 5504 if (It == AnonymousDeclarationNumbers.end()) { 5505 auto *DC = D->getLexicalDeclContext(); 5506 numberAnonymousDeclsWithin(DC, [&](const NamedDecl *ND, unsigned Number) { 5507 AnonymousDeclarationNumbers[ND] = Number; 5508 }); 5509 5510 It = AnonymousDeclarationNumbers.find(D); 5511 assert(It != AnonymousDeclarationNumbers.end() && 5512 "declaration not found within its lexical context"); 5513 } 5514 5515 return It->second; 5516 } 5517 5518 void ASTRecordWriter::AddDeclarationNameLoc(const DeclarationNameLoc &DNLoc, 5519 DeclarationName Name) { 5520 switch (Name.getNameKind()) { 5521 case DeclarationName::CXXConstructorName: 5522 case DeclarationName::CXXDestructorName: 5523 case DeclarationName::CXXConversionFunctionName: 5524 AddTypeSourceInfo(DNLoc.getNamedTypeInfo()); 5525 break; 5526 5527 case DeclarationName::CXXOperatorName: 5528 AddSourceRange(DNLoc.getCXXOperatorNameRange()); 5529 break; 5530 5531 case DeclarationName::CXXLiteralOperatorName: 5532 AddSourceLocation(DNLoc.getCXXLiteralOperatorNameLoc()); 5533 break; 5534 5535 case DeclarationName::Identifier: 5536 case DeclarationName::ObjCZeroArgSelector: 5537 case DeclarationName::ObjCOneArgSelector: 5538 case DeclarationName::ObjCMultiArgSelector: 5539 case DeclarationName::CXXUsingDirective: 5540 case DeclarationName::CXXDeductionGuideName: 5541 break; 5542 } 5543 } 5544 5545 void ASTRecordWriter::AddDeclarationNameInfo( 5546 const DeclarationNameInfo &NameInfo) { 5547 AddDeclarationName(NameInfo.getName()); 5548 AddSourceLocation(NameInfo.getLoc()); 5549 AddDeclarationNameLoc(NameInfo.getInfo(), NameInfo.getName()); 5550 } 5551 5552 void ASTRecordWriter::AddQualifierInfo(const QualifierInfo &Info) { 5553 AddNestedNameSpecifierLoc(Info.QualifierLoc); 5554 Record->push_back(Info.NumTemplParamLists); 5555 for (unsigned i = 0, e = Info.NumTemplParamLists; i != e; ++i) 5556 AddTemplateParameterList(Info.TemplParamLists[i]); 5557 } 5558 5559 void ASTRecordWriter::AddNestedNameSpecifierLoc(NestedNameSpecifierLoc NNS) { 5560 // Nested name specifiers usually aren't too long. I think that 8 would 5561 // typically accommodate the vast majority. 5562 SmallVector<NestedNameSpecifierLoc , 8> NestedNames; 5563 5564 // Push each of the nested-name-specifiers's onto a stack for 5565 // serialization in reverse order. 5566 while (NNS) { 5567 NestedNames.push_back(NNS); 5568 NNS = NNS.getPrefix(); 5569 } 5570 5571 Record->push_back(NestedNames.size()); 5572 while(!NestedNames.empty()) { 5573 NNS = NestedNames.pop_back_val(); 5574 NestedNameSpecifier::SpecifierKind Kind 5575 = NNS.getNestedNameSpecifier()->getKind(); 5576 Record->push_back(Kind); 5577 switch (Kind) { 5578 case NestedNameSpecifier::Identifier: 5579 AddIdentifierRef(NNS.getNestedNameSpecifier()->getAsIdentifier()); 5580 AddSourceRange(NNS.getLocalSourceRange()); 5581 break; 5582 5583 case NestedNameSpecifier::Namespace: 5584 AddDeclRef(NNS.getNestedNameSpecifier()->getAsNamespace()); 5585 AddSourceRange(NNS.getLocalSourceRange()); 5586 break; 5587 5588 case NestedNameSpecifier::NamespaceAlias: 5589 AddDeclRef(NNS.getNestedNameSpecifier()->getAsNamespaceAlias()); 5590 AddSourceRange(NNS.getLocalSourceRange()); 5591 break; 5592 5593 case NestedNameSpecifier::TypeSpec: 5594 case NestedNameSpecifier::TypeSpecWithTemplate: 5595 Record->push_back(Kind == NestedNameSpecifier::TypeSpecWithTemplate); 5596 AddTypeRef(NNS.getTypeLoc().getType()); 5597 AddTypeLoc(NNS.getTypeLoc()); 5598 AddSourceLocation(NNS.getLocalSourceRange().getEnd()); 5599 break; 5600 5601 case NestedNameSpecifier::Global: 5602 AddSourceLocation(NNS.getLocalSourceRange().getEnd()); 5603 break; 5604 5605 case NestedNameSpecifier::Super: 5606 AddDeclRef(NNS.getNestedNameSpecifier()->getAsRecordDecl()); 5607 AddSourceRange(NNS.getLocalSourceRange()); 5608 break; 5609 } 5610 } 5611 } 5612 5613 void ASTRecordWriter::AddTemplateParameterList( 5614 const TemplateParameterList *TemplateParams) { 5615 assert(TemplateParams && "No TemplateParams!"); 5616 AddSourceLocation(TemplateParams->getTemplateLoc()); 5617 AddSourceLocation(TemplateParams->getLAngleLoc()); 5618 AddSourceLocation(TemplateParams->getRAngleLoc()); 5619 5620 Record->push_back(TemplateParams->size()); 5621 for (const auto &P : *TemplateParams) 5622 AddDeclRef(P); 5623 if (const Expr *RequiresClause = TemplateParams->getRequiresClause()) { 5624 Record->push_back(true); 5625 AddStmt(const_cast<Expr*>(RequiresClause)); 5626 } else { 5627 Record->push_back(false); 5628 } 5629 } 5630 5631 /// Emit a template argument list. 5632 void ASTRecordWriter::AddTemplateArgumentList( 5633 const TemplateArgumentList *TemplateArgs) { 5634 assert(TemplateArgs && "No TemplateArgs!"); 5635 Record->push_back(TemplateArgs->size()); 5636 for (int i = 0, e = TemplateArgs->size(); i != e; ++i) 5637 AddTemplateArgument(TemplateArgs->get(i)); 5638 } 5639 5640 void ASTRecordWriter::AddASTTemplateArgumentListInfo( 5641 const ASTTemplateArgumentListInfo *ASTTemplArgList) { 5642 assert(ASTTemplArgList && "No ASTTemplArgList!"); 5643 AddSourceLocation(ASTTemplArgList->LAngleLoc); 5644 AddSourceLocation(ASTTemplArgList->RAngleLoc); 5645 Record->push_back(ASTTemplArgList->NumTemplateArgs); 5646 const TemplateArgumentLoc *TemplArgs = ASTTemplArgList->getTemplateArgs(); 5647 for (int i = 0, e = ASTTemplArgList->NumTemplateArgs; i != e; ++i) 5648 AddTemplateArgumentLoc(TemplArgs[i]); 5649 } 5650 5651 void ASTRecordWriter::AddUnresolvedSet(const ASTUnresolvedSet &Set) { 5652 Record->push_back(Set.size()); 5653 for (ASTUnresolvedSet::const_iterator 5654 I = Set.begin(), E = Set.end(); I != E; ++I) { 5655 AddDeclRef(I.getDecl()); 5656 Record->push_back(I.getAccess()); 5657 } 5658 } 5659 5660 // FIXME: Move this out of the main ASTRecordWriter interface. 5661 void ASTRecordWriter::AddCXXBaseSpecifier(const CXXBaseSpecifier &Base) { 5662 Record->push_back(Base.isVirtual()); 5663 Record->push_back(Base.isBaseOfClass()); 5664 Record->push_back(Base.getAccessSpecifierAsWritten()); 5665 Record->push_back(Base.getInheritConstructors()); 5666 AddTypeSourceInfo(Base.getTypeSourceInfo()); 5667 AddSourceRange(Base.getSourceRange()); 5668 AddSourceLocation(Base.isPackExpansion()? Base.getEllipsisLoc() 5669 : SourceLocation()); 5670 } 5671 5672 static uint64_t EmitCXXBaseSpecifiers(ASTWriter &W, 5673 ArrayRef<CXXBaseSpecifier> Bases) { 5674 ASTWriter::RecordData Record; 5675 ASTRecordWriter Writer(W, Record); 5676 Writer.push_back(Bases.size()); 5677 5678 for (auto &Base : Bases) 5679 Writer.AddCXXBaseSpecifier(Base); 5680 5681 return Writer.Emit(serialization::DECL_CXX_BASE_SPECIFIERS); 5682 } 5683 5684 // FIXME: Move this out of the main ASTRecordWriter interface. 5685 void ASTRecordWriter::AddCXXBaseSpecifiers(ArrayRef<CXXBaseSpecifier> Bases) { 5686 AddOffset(EmitCXXBaseSpecifiers(*Writer, Bases)); 5687 } 5688 5689 static uint64_t 5690 EmitCXXCtorInitializers(ASTWriter &W, 5691 ArrayRef<CXXCtorInitializer *> CtorInits) { 5692 ASTWriter::RecordData Record; 5693 ASTRecordWriter Writer(W, Record); 5694 Writer.push_back(CtorInits.size()); 5695 5696 for (auto *Init : CtorInits) { 5697 if (Init->isBaseInitializer()) { 5698 Writer.push_back(CTOR_INITIALIZER_BASE); 5699 Writer.AddTypeSourceInfo(Init->getTypeSourceInfo()); 5700 Writer.push_back(Init->isBaseVirtual()); 5701 } else if (Init->isDelegatingInitializer()) { 5702 Writer.push_back(CTOR_INITIALIZER_DELEGATING); 5703 Writer.AddTypeSourceInfo(Init->getTypeSourceInfo()); 5704 } else if (Init->isMemberInitializer()){ 5705 Writer.push_back(CTOR_INITIALIZER_MEMBER); 5706 Writer.AddDeclRef(Init->getMember()); 5707 } else { 5708 Writer.push_back(CTOR_INITIALIZER_INDIRECT_MEMBER); 5709 Writer.AddDeclRef(Init->getIndirectMember()); 5710 } 5711 5712 Writer.AddSourceLocation(Init->getMemberLocation()); 5713 Writer.AddStmt(Init->getInit()); 5714 Writer.AddSourceLocation(Init->getLParenLoc()); 5715 Writer.AddSourceLocation(Init->getRParenLoc()); 5716 Writer.push_back(Init->isWritten()); 5717 if (Init->isWritten()) 5718 Writer.push_back(Init->getSourceOrder()); 5719 } 5720 5721 return Writer.Emit(serialization::DECL_CXX_CTOR_INITIALIZERS); 5722 } 5723 5724 // FIXME: Move this out of the main ASTRecordWriter interface. 5725 void ASTRecordWriter::AddCXXCtorInitializers( 5726 ArrayRef<CXXCtorInitializer *> CtorInits) { 5727 AddOffset(EmitCXXCtorInitializers(*Writer, CtorInits)); 5728 } 5729 5730 void ASTRecordWriter::AddCXXDefinitionData(const CXXRecordDecl *D) { 5731 auto &Data = D->data(); 5732 Record->push_back(Data.IsLambda); 5733 5734 #define FIELD(Name, Width, Merge) \ 5735 Record->push_back(Data.Name); 5736 #include "clang/AST/CXXRecordDeclDefinitionBits.def" 5737 5738 // getODRHash will compute the ODRHash if it has not been previously computed. 5739 Record->push_back(D->getODRHash()); 5740 bool ModulesDebugInfo = 5741 Writer->Context->getLangOpts().ModulesDebugInfo && !D->isDependentType(); 5742 Record->push_back(ModulesDebugInfo); 5743 if (ModulesDebugInfo) 5744 Writer->ModularCodegenDecls.push_back(Writer->GetDeclRef(D)); 5745 5746 // IsLambda bit is already saved. 5747 5748 Record->push_back(Data.NumBases); 5749 if (Data.NumBases > 0) 5750 AddCXXBaseSpecifiers(Data.bases()); 5751 5752 // FIXME: Make VBases lazily computed when needed to avoid storing them. 5753 Record->push_back(Data.NumVBases); 5754 if (Data.NumVBases > 0) 5755 AddCXXBaseSpecifiers(Data.vbases()); 5756 5757 AddUnresolvedSet(Data.Conversions.get(*Writer->Context)); 5758 Record->push_back(Data.ComputedVisibleConversions); 5759 if (Data.ComputedVisibleConversions) 5760 AddUnresolvedSet(Data.VisibleConversions.get(*Writer->Context)); 5761 // Data.Definition is the owning decl, no need to write it. 5762 AddDeclRef(D->getFirstFriend()); 5763 5764 // Add lambda-specific data. 5765 if (Data.IsLambda) { 5766 auto &Lambda = D->getLambdaData(); 5767 Record->push_back(Lambda.DependencyKind); 5768 Record->push_back(Lambda.IsGenericLambda); 5769 Record->push_back(Lambda.CaptureDefault); 5770 Record->push_back(Lambda.NumCaptures); 5771 Record->push_back(Lambda.NumExplicitCaptures); 5772 Record->push_back(Lambda.HasKnownInternalLinkage); 5773 Record->push_back(Lambda.ManglingNumber); 5774 Record->push_back(D->getDeviceLambdaManglingNumber()); 5775 AddDeclRef(D->getLambdaContextDecl()); 5776 AddTypeSourceInfo(Lambda.MethodTyInfo); 5777 for (unsigned I = 0, N = Lambda.NumCaptures; I != N; ++I) { 5778 const LambdaCapture &Capture = Lambda.Captures[I]; 5779 AddSourceLocation(Capture.getLocation()); 5780 Record->push_back(Capture.isImplicit()); 5781 Record->push_back(Capture.getCaptureKind()); 5782 switch (Capture.getCaptureKind()) { 5783 case LCK_StarThis: 5784 case LCK_This: 5785 case LCK_VLAType: 5786 break; 5787 case LCK_ByCopy: 5788 case LCK_ByRef: 5789 VarDecl *Var = 5790 Capture.capturesVariable() ? Capture.getCapturedVar() : nullptr; 5791 AddDeclRef(Var); 5792 AddSourceLocation(Capture.isPackExpansion() ? Capture.getEllipsisLoc() 5793 : SourceLocation()); 5794 break; 5795 } 5796 } 5797 } 5798 } 5799 5800 void ASTRecordWriter::AddVarDeclInit(const VarDecl *VD) { 5801 const Expr *Init = VD->getInit(); 5802 if (!Init) { 5803 push_back(0); 5804 return; 5805 } 5806 5807 unsigned Val = 1; 5808 if (EvaluatedStmt *ES = VD->getEvaluatedStmt()) { 5809 Val |= (ES->HasConstantInitialization ? 2 : 0); 5810 Val |= (ES->HasConstantDestruction ? 4 : 0); 5811 // FIXME: Also emit the constant initializer value. 5812 } 5813 push_back(Val); 5814 writeStmtRef(Init); 5815 } 5816 5817 void ASTWriter::ReaderInitialized(ASTReader *Reader) { 5818 assert(Reader && "Cannot remove chain"); 5819 assert((!Chain || Chain == Reader) && "Cannot replace chain"); 5820 assert(FirstDeclID == NextDeclID && 5821 FirstTypeID == NextTypeID && 5822 FirstIdentID == NextIdentID && 5823 FirstMacroID == NextMacroID && 5824 FirstSubmoduleID == NextSubmoduleID && 5825 FirstSelectorID == NextSelectorID && 5826 "Setting chain after writing has started."); 5827 5828 Chain = Reader; 5829 5830 // Note, this will get called multiple times, once one the reader starts up 5831 // and again each time it's done reading a PCH or module. 5832 FirstDeclID = NUM_PREDEF_DECL_IDS + Chain->getTotalNumDecls(); 5833 FirstTypeID = NUM_PREDEF_TYPE_IDS + Chain->getTotalNumTypes(); 5834 FirstIdentID = NUM_PREDEF_IDENT_IDS + Chain->getTotalNumIdentifiers(); 5835 FirstMacroID = NUM_PREDEF_MACRO_IDS + Chain->getTotalNumMacros(); 5836 FirstSubmoduleID = NUM_PREDEF_SUBMODULE_IDS + Chain->getTotalNumSubmodules(); 5837 FirstSelectorID = NUM_PREDEF_SELECTOR_IDS + Chain->getTotalNumSelectors(); 5838 NextDeclID = FirstDeclID; 5839 NextTypeID = FirstTypeID; 5840 NextIdentID = FirstIdentID; 5841 NextMacroID = FirstMacroID; 5842 NextSelectorID = FirstSelectorID; 5843 NextSubmoduleID = FirstSubmoduleID; 5844 } 5845 5846 void ASTWriter::IdentifierRead(IdentID ID, IdentifierInfo *II) { 5847 // Always keep the highest ID. See \p TypeRead() for more information. 5848 IdentID &StoredID = IdentifierIDs[II]; 5849 if (ID > StoredID) 5850 StoredID = ID; 5851 } 5852 5853 void ASTWriter::MacroRead(serialization::MacroID ID, MacroInfo *MI) { 5854 // Always keep the highest ID. See \p TypeRead() for more information. 5855 MacroID &StoredID = MacroIDs[MI]; 5856 if (ID > StoredID) 5857 StoredID = ID; 5858 } 5859 5860 void ASTWriter::TypeRead(TypeIdx Idx, QualType T) { 5861 // Always take the highest-numbered type index. This copes with an interesting 5862 // case for chained AST writing where we schedule writing the type and then, 5863 // later, deserialize the type from another AST. In this case, we want to 5864 // keep the higher-numbered entry so that we can properly write it out to 5865 // the AST file. 5866 TypeIdx &StoredIdx = TypeIdxs[T]; 5867 if (Idx.getIndex() >= StoredIdx.getIndex()) 5868 StoredIdx = Idx; 5869 } 5870 5871 void ASTWriter::SelectorRead(SelectorID ID, Selector S) { 5872 // Always keep the highest ID. See \p TypeRead() for more information. 5873 SelectorID &StoredID = SelectorIDs[S]; 5874 if (ID > StoredID) 5875 StoredID = ID; 5876 } 5877 5878 void ASTWriter::MacroDefinitionRead(serialization::PreprocessedEntityID ID, 5879 MacroDefinitionRecord *MD) { 5880 assert(MacroDefinitions.find(MD) == MacroDefinitions.end()); 5881 MacroDefinitions[MD] = ID; 5882 } 5883 5884 void ASTWriter::ModuleRead(serialization::SubmoduleID ID, Module *Mod) { 5885 assert(SubmoduleIDs.find(Mod) == SubmoduleIDs.end()); 5886 SubmoduleIDs[Mod] = ID; 5887 } 5888 5889 void ASTWriter::CompletedTagDefinition(const TagDecl *D) { 5890 if (Chain && Chain->isProcessingUpdateRecords()) return; 5891 assert(D->isCompleteDefinition()); 5892 assert(!WritingAST && "Already writing the AST!"); 5893 if (auto *RD = dyn_cast<CXXRecordDecl>(D)) { 5894 // We are interested when a PCH decl is modified. 5895 if (RD->isFromASTFile()) { 5896 // A forward reference was mutated into a definition. Rewrite it. 5897 // FIXME: This happens during template instantiation, should we 5898 // have created a new definition decl instead ? 5899 assert(isTemplateInstantiation(RD->getTemplateSpecializationKind()) && 5900 "completed a tag from another module but not by instantiation?"); 5901 DeclUpdates[RD].push_back( 5902 DeclUpdate(UPD_CXX_INSTANTIATED_CLASS_DEFINITION)); 5903 } 5904 } 5905 } 5906 5907 static bool isImportedDeclContext(ASTReader *Chain, const Decl *D) { 5908 if (D->isFromASTFile()) 5909 return true; 5910 5911 // The predefined __va_list_tag struct is imported if we imported any decls. 5912 // FIXME: This is a gross hack. 5913 return D == D->getASTContext().getVaListTagDecl(); 5914 } 5915 5916 void ASTWriter::AddedVisibleDecl(const DeclContext *DC, const Decl *D) { 5917 if (Chain && Chain->isProcessingUpdateRecords()) return; 5918 assert(DC->isLookupContext() && 5919 "Should not add lookup results to non-lookup contexts!"); 5920 5921 // TU is handled elsewhere. 5922 if (isa<TranslationUnitDecl>(DC)) 5923 return; 5924 5925 // Namespaces are handled elsewhere, except for template instantiations of 5926 // FunctionTemplateDecls in namespaces. We are interested in cases where the 5927 // local instantiations are added to an imported context. Only happens when 5928 // adding ADL lookup candidates, for example templated friends. 5929 if (isa<NamespaceDecl>(DC) && D->getFriendObjectKind() == Decl::FOK_None && 5930 !isa<FunctionTemplateDecl>(D)) 5931 return; 5932 5933 // We're only interested in cases where a local declaration is added to an 5934 // imported context. 5935 if (D->isFromASTFile() || !isImportedDeclContext(Chain, cast<Decl>(DC))) 5936 return; 5937 5938 assert(DC == DC->getPrimaryContext() && "added to non-primary context"); 5939 assert(!getDefinitiveDeclContext(DC) && "DeclContext not definitive!"); 5940 assert(!WritingAST && "Already writing the AST!"); 5941 if (UpdatedDeclContexts.insert(DC) && !cast<Decl>(DC)->isFromASTFile()) { 5942 // We're adding a visible declaration to a predefined decl context. Ensure 5943 // that we write out all of its lookup results so we don't get a nasty 5944 // surprise when we try to emit its lookup table. 5945 llvm::append_range(DeclsToEmitEvenIfUnreferenced, DC->decls()); 5946 } 5947 DeclsToEmitEvenIfUnreferenced.push_back(D); 5948 } 5949 5950 void ASTWriter::AddedCXXImplicitMember(const CXXRecordDecl *RD, const Decl *D) { 5951 if (Chain && Chain->isProcessingUpdateRecords()) return; 5952 assert(D->isImplicit()); 5953 5954 // We're only interested in cases where a local declaration is added to an 5955 // imported context. 5956 if (D->isFromASTFile() || !isImportedDeclContext(Chain, RD)) 5957 return; 5958 5959 if (!isa<CXXMethodDecl>(D)) 5960 return; 5961 5962 // A decl coming from PCH was modified. 5963 assert(RD->isCompleteDefinition()); 5964 assert(!WritingAST && "Already writing the AST!"); 5965 DeclUpdates[RD].push_back(DeclUpdate(UPD_CXX_ADDED_IMPLICIT_MEMBER, D)); 5966 } 5967 5968 void ASTWriter::ResolvedExceptionSpec(const FunctionDecl *FD) { 5969 if (Chain && Chain->isProcessingUpdateRecords()) return; 5970 assert(!DoneWritingDeclsAndTypes && "Already done writing updates!"); 5971 if (!Chain) return; 5972 Chain->forEachImportedKeyDecl(FD, [&](const Decl *D) { 5973 // If we don't already know the exception specification for this redecl 5974 // chain, add an update record for it. 5975 if (isUnresolvedExceptionSpec(cast<FunctionDecl>(D) 5976 ->getType() 5977 ->castAs<FunctionProtoType>() 5978 ->getExceptionSpecType())) 5979 DeclUpdates[D].push_back(UPD_CXX_RESOLVED_EXCEPTION_SPEC); 5980 }); 5981 } 5982 5983 void ASTWriter::DeducedReturnType(const FunctionDecl *FD, QualType ReturnType) { 5984 if (Chain && Chain->isProcessingUpdateRecords()) return; 5985 assert(!WritingAST && "Already writing the AST!"); 5986 if (!Chain) return; 5987 Chain->forEachImportedKeyDecl(FD, [&](const Decl *D) { 5988 DeclUpdates[D].push_back( 5989 DeclUpdate(UPD_CXX_DEDUCED_RETURN_TYPE, ReturnType)); 5990 }); 5991 } 5992 5993 void ASTWriter::ResolvedOperatorDelete(const CXXDestructorDecl *DD, 5994 const FunctionDecl *Delete, 5995 Expr *ThisArg) { 5996 if (Chain && Chain->isProcessingUpdateRecords()) return; 5997 assert(!WritingAST && "Already writing the AST!"); 5998 assert(Delete && "Not given an operator delete"); 5999 if (!Chain) return; 6000 Chain->forEachImportedKeyDecl(DD, [&](const Decl *D) { 6001 DeclUpdates[D].push_back(DeclUpdate(UPD_CXX_RESOLVED_DTOR_DELETE, Delete)); 6002 }); 6003 } 6004 6005 void ASTWriter::CompletedImplicitDefinition(const FunctionDecl *D) { 6006 if (Chain && Chain->isProcessingUpdateRecords()) return; 6007 assert(!WritingAST && "Already writing the AST!"); 6008 if (!D->isFromASTFile()) 6009 return; // Declaration not imported from PCH. 6010 6011 // Implicit function decl from a PCH was defined. 6012 DeclUpdates[D].push_back(DeclUpdate(UPD_CXX_ADDED_FUNCTION_DEFINITION)); 6013 } 6014 6015 void ASTWriter::VariableDefinitionInstantiated(const VarDecl *D) { 6016 if (Chain && Chain->isProcessingUpdateRecords()) return; 6017 assert(!WritingAST && "Already writing the AST!"); 6018 if (!D->isFromASTFile()) 6019 return; 6020 6021 DeclUpdates[D].push_back(DeclUpdate(UPD_CXX_ADDED_VAR_DEFINITION)); 6022 } 6023 6024 void ASTWriter::FunctionDefinitionInstantiated(const FunctionDecl *D) { 6025 if (Chain && Chain->isProcessingUpdateRecords()) return; 6026 assert(!WritingAST && "Already writing the AST!"); 6027 if (!D->isFromASTFile()) 6028 return; 6029 6030 DeclUpdates[D].push_back(DeclUpdate(UPD_CXX_ADDED_FUNCTION_DEFINITION)); 6031 } 6032 6033 void ASTWriter::InstantiationRequested(const ValueDecl *D) { 6034 if (Chain && Chain->isProcessingUpdateRecords()) return; 6035 assert(!WritingAST && "Already writing the AST!"); 6036 if (!D->isFromASTFile()) 6037 return; 6038 6039 // Since the actual instantiation is delayed, this really means that we need 6040 // to update the instantiation location. 6041 SourceLocation POI; 6042 if (auto *VD = dyn_cast<VarDecl>(D)) 6043 POI = VD->getPointOfInstantiation(); 6044 else 6045 POI = cast<FunctionDecl>(D)->getPointOfInstantiation(); 6046 DeclUpdates[D].push_back(DeclUpdate(UPD_CXX_POINT_OF_INSTANTIATION, POI)); 6047 } 6048 6049 void ASTWriter::DefaultArgumentInstantiated(const ParmVarDecl *D) { 6050 if (Chain && Chain->isProcessingUpdateRecords()) return; 6051 assert(!WritingAST && "Already writing the AST!"); 6052 if (!D->isFromASTFile()) 6053 return; 6054 6055 DeclUpdates[D].push_back( 6056 DeclUpdate(UPD_CXX_INSTANTIATED_DEFAULT_ARGUMENT, D)); 6057 } 6058 6059 void ASTWriter::DefaultMemberInitializerInstantiated(const FieldDecl *D) { 6060 assert(!WritingAST && "Already writing the AST!"); 6061 if (!D->isFromASTFile()) 6062 return; 6063 6064 DeclUpdates[D].push_back( 6065 DeclUpdate(UPD_CXX_INSTANTIATED_DEFAULT_MEMBER_INITIALIZER, D)); 6066 } 6067 6068 void ASTWriter::AddedObjCCategoryToInterface(const ObjCCategoryDecl *CatD, 6069 const ObjCInterfaceDecl *IFD) { 6070 if (Chain && Chain->isProcessingUpdateRecords()) return; 6071 assert(!WritingAST && "Already writing the AST!"); 6072 if (!IFD->isFromASTFile()) 6073 return; // Declaration not imported from PCH. 6074 6075 assert(IFD->getDefinition() && "Category on a class without a definition?"); 6076 ObjCClassesWithCategories.insert( 6077 const_cast<ObjCInterfaceDecl *>(IFD->getDefinition())); 6078 } 6079 6080 void ASTWriter::DeclarationMarkedUsed(const Decl *D) { 6081 if (Chain && Chain->isProcessingUpdateRecords()) return; 6082 assert(!WritingAST && "Already writing the AST!"); 6083 6084 // If there is *any* declaration of the entity that's not from an AST file, 6085 // we can skip writing the update record. We make sure that isUsed() triggers 6086 // completion of the redeclaration chain of the entity. 6087 for (auto Prev = D->getMostRecentDecl(); Prev; Prev = Prev->getPreviousDecl()) 6088 if (IsLocalDecl(Prev)) 6089 return; 6090 6091 DeclUpdates[D].push_back(DeclUpdate(UPD_DECL_MARKED_USED)); 6092 } 6093 6094 void ASTWriter::DeclarationMarkedOpenMPThreadPrivate(const Decl *D) { 6095 if (Chain && Chain->isProcessingUpdateRecords()) return; 6096 assert(!WritingAST && "Already writing the AST!"); 6097 if (!D->isFromASTFile()) 6098 return; 6099 6100 DeclUpdates[D].push_back(DeclUpdate(UPD_DECL_MARKED_OPENMP_THREADPRIVATE)); 6101 } 6102 6103 void ASTWriter::DeclarationMarkedOpenMPAllocate(const Decl *D, const Attr *A) { 6104 if (Chain && Chain->isProcessingUpdateRecords()) return; 6105 assert(!WritingAST && "Already writing the AST!"); 6106 if (!D->isFromASTFile()) 6107 return; 6108 6109 DeclUpdates[D].push_back(DeclUpdate(UPD_DECL_MARKED_OPENMP_ALLOCATE, A)); 6110 } 6111 6112 void ASTWriter::DeclarationMarkedOpenMPDeclareTarget(const Decl *D, 6113 const Attr *Attr) { 6114 if (Chain && Chain->isProcessingUpdateRecords()) return; 6115 assert(!WritingAST && "Already writing the AST!"); 6116 if (!D->isFromASTFile()) 6117 return; 6118 6119 DeclUpdates[D].push_back( 6120 DeclUpdate(UPD_DECL_MARKED_OPENMP_DECLARETARGET, Attr)); 6121 } 6122 6123 void ASTWriter::RedefinedHiddenDefinition(const NamedDecl *D, Module *M) { 6124 if (Chain && Chain->isProcessingUpdateRecords()) return; 6125 assert(!WritingAST && "Already writing the AST!"); 6126 assert(!D->isUnconditionallyVisible() && "expected a hidden declaration"); 6127 DeclUpdates[D].push_back(DeclUpdate(UPD_DECL_EXPORTED, M)); 6128 } 6129 6130 void ASTWriter::AddedAttributeToRecord(const Attr *Attr, 6131 const RecordDecl *Record) { 6132 if (Chain && Chain->isProcessingUpdateRecords()) return; 6133 assert(!WritingAST && "Already writing the AST!"); 6134 if (!Record->isFromASTFile()) 6135 return; 6136 DeclUpdates[Record].push_back(DeclUpdate(UPD_ADDED_ATTR_TO_RECORD, Attr)); 6137 } 6138 6139 void ASTWriter::AddedCXXTemplateSpecialization( 6140 const ClassTemplateDecl *TD, const ClassTemplateSpecializationDecl *D) { 6141 assert(!WritingAST && "Already writing the AST!"); 6142 6143 if (!TD->getFirstDecl()->isFromASTFile()) 6144 return; 6145 if (Chain && Chain->isProcessingUpdateRecords()) 6146 return; 6147 6148 DeclsToEmitEvenIfUnreferenced.push_back(D); 6149 } 6150 6151 void ASTWriter::AddedCXXTemplateSpecialization( 6152 const VarTemplateDecl *TD, const VarTemplateSpecializationDecl *D) { 6153 assert(!WritingAST && "Already writing the AST!"); 6154 6155 if (!TD->getFirstDecl()->isFromASTFile()) 6156 return; 6157 if (Chain && Chain->isProcessingUpdateRecords()) 6158 return; 6159 6160 DeclsToEmitEvenIfUnreferenced.push_back(D); 6161 } 6162 6163 void ASTWriter::AddedCXXTemplateSpecialization(const FunctionTemplateDecl *TD, 6164 const FunctionDecl *D) { 6165 assert(!WritingAST && "Already writing the AST!"); 6166 6167 if (!TD->getFirstDecl()->isFromASTFile()) 6168 return; 6169 if (Chain && Chain->isProcessingUpdateRecords()) 6170 return; 6171 6172 DeclsToEmitEvenIfUnreferenced.push_back(D); 6173 } 6174 6175 //===----------------------------------------------------------------------===// 6176 //// OMPClause Serialization 6177 ////===----------------------------------------------------------------------===// 6178 6179 namespace { 6180 6181 class OMPClauseWriter : public OMPClauseVisitor<OMPClauseWriter> { 6182 ASTRecordWriter &Record; 6183 6184 public: 6185 OMPClauseWriter(ASTRecordWriter &Record) : Record(Record) {} 6186 #define GEN_CLANG_CLAUSE_CLASS 6187 #define CLAUSE_CLASS(Enum, Str, Class) void Visit##Class(Class *S); 6188 #include "llvm/Frontend/OpenMP/OMP.inc" 6189 void writeClause(OMPClause *C); 6190 void VisitOMPClauseWithPreInit(OMPClauseWithPreInit *C); 6191 void VisitOMPClauseWithPostUpdate(OMPClauseWithPostUpdate *C); 6192 }; 6193 6194 } 6195 6196 void ASTRecordWriter::writeOMPClause(OMPClause *C) { 6197 OMPClauseWriter(*this).writeClause(C); 6198 } 6199 6200 void OMPClauseWriter::writeClause(OMPClause *C) { 6201 Record.push_back(unsigned(C->getClauseKind())); 6202 Visit(C); 6203 Record.AddSourceLocation(C->getBeginLoc()); 6204 Record.AddSourceLocation(C->getEndLoc()); 6205 } 6206 6207 void OMPClauseWriter::VisitOMPClauseWithPreInit(OMPClauseWithPreInit *C) { 6208 Record.push_back(uint64_t(C->getCaptureRegion())); 6209 Record.AddStmt(C->getPreInitStmt()); 6210 } 6211 6212 void OMPClauseWriter::VisitOMPClauseWithPostUpdate(OMPClauseWithPostUpdate *C) { 6213 VisitOMPClauseWithPreInit(C); 6214 Record.AddStmt(C->getPostUpdateExpr()); 6215 } 6216 6217 void OMPClauseWriter::VisitOMPIfClause(OMPIfClause *C) { 6218 VisitOMPClauseWithPreInit(C); 6219 Record.push_back(uint64_t(C->getNameModifier())); 6220 Record.AddSourceLocation(C->getNameModifierLoc()); 6221 Record.AddSourceLocation(C->getColonLoc()); 6222 Record.AddStmt(C->getCondition()); 6223 Record.AddSourceLocation(C->getLParenLoc()); 6224 } 6225 6226 void OMPClauseWriter::VisitOMPFinalClause(OMPFinalClause *C) { 6227 VisitOMPClauseWithPreInit(C); 6228 Record.AddStmt(C->getCondition()); 6229 Record.AddSourceLocation(C->getLParenLoc()); 6230 } 6231 6232 void OMPClauseWriter::VisitOMPNumThreadsClause(OMPNumThreadsClause *C) { 6233 VisitOMPClauseWithPreInit(C); 6234 Record.AddStmt(C->getNumThreads()); 6235 Record.AddSourceLocation(C->getLParenLoc()); 6236 } 6237 6238 void OMPClauseWriter::VisitOMPSafelenClause(OMPSafelenClause *C) { 6239 Record.AddStmt(C->getSafelen()); 6240 Record.AddSourceLocation(C->getLParenLoc()); 6241 } 6242 6243 void OMPClauseWriter::VisitOMPSimdlenClause(OMPSimdlenClause *C) { 6244 Record.AddStmt(C->getSimdlen()); 6245 Record.AddSourceLocation(C->getLParenLoc()); 6246 } 6247 6248 void OMPClauseWriter::VisitOMPSizesClause(OMPSizesClause *C) { 6249 Record.push_back(C->getNumSizes()); 6250 for (Expr *Size : C->getSizesRefs()) 6251 Record.AddStmt(Size); 6252 Record.AddSourceLocation(C->getLParenLoc()); 6253 } 6254 6255 void OMPClauseWriter::VisitOMPFullClause(OMPFullClause *C) {} 6256 6257 void OMPClauseWriter::VisitOMPPartialClause(OMPPartialClause *C) { 6258 Record.AddStmt(C->getFactor()); 6259 Record.AddSourceLocation(C->getLParenLoc()); 6260 } 6261 6262 void OMPClauseWriter::VisitOMPAllocatorClause(OMPAllocatorClause *C) { 6263 Record.AddStmt(C->getAllocator()); 6264 Record.AddSourceLocation(C->getLParenLoc()); 6265 } 6266 6267 void OMPClauseWriter::VisitOMPCollapseClause(OMPCollapseClause *C) { 6268 Record.AddStmt(C->getNumForLoops()); 6269 Record.AddSourceLocation(C->getLParenLoc()); 6270 } 6271 6272 void OMPClauseWriter::VisitOMPDetachClause(OMPDetachClause *C) { 6273 Record.AddStmt(C->getEventHandler()); 6274 Record.AddSourceLocation(C->getLParenLoc()); 6275 } 6276 6277 void OMPClauseWriter::VisitOMPDefaultClause(OMPDefaultClause *C) { 6278 Record.push_back(unsigned(C->getDefaultKind())); 6279 Record.AddSourceLocation(C->getLParenLoc()); 6280 Record.AddSourceLocation(C->getDefaultKindKwLoc()); 6281 } 6282 6283 void OMPClauseWriter::VisitOMPProcBindClause(OMPProcBindClause *C) { 6284 Record.push_back(unsigned(C->getProcBindKind())); 6285 Record.AddSourceLocation(C->getLParenLoc()); 6286 Record.AddSourceLocation(C->getProcBindKindKwLoc()); 6287 } 6288 6289 void OMPClauseWriter::VisitOMPScheduleClause(OMPScheduleClause *C) { 6290 VisitOMPClauseWithPreInit(C); 6291 Record.push_back(C->getScheduleKind()); 6292 Record.push_back(C->getFirstScheduleModifier()); 6293 Record.push_back(C->getSecondScheduleModifier()); 6294 Record.AddStmt(C->getChunkSize()); 6295 Record.AddSourceLocation(C->getLParenLoc()); 6296 Record.AddSourceLocation(C->getFirstScheduleModifierLoc()); 6297 Record.AddSourceLocation(C->getSecondScheduleModifierLoc()); 6298 Record.AddSourceLocation(C->getScheduleKindLoc()); 6299 Record.AddSourceLocation(C->getCommaLoc()); 6300 } 6301 6302 void OMPClauseWriter::VisitOMPOrderedClause(OMPOrderedClause *C) { 6303 Record.push_back(C->getLoopNumIterations().size()); 6304 Record.AddStmt(C->getNumForLoops()); 6305 for (Expr *NumIter : C->getLoopNumIterations()) 6306 Record.AddStmt(NumIter); 6307 for (unsigned I = 0, E = C->getLoopNumIterations().size(); I <E; ++I) 6308 Record.AddStmt(C->getLoopCounter(I)); 6309 Record.AddSourceLocation(C->getLParenLoc()); 6310 } 6311 6312 void OMPClauseWriter::VisitOMPNowaitClause(OMPNowaitClause *) {} 6313 6314 void OMPClauseWriter::VisitOMPUntiedClause(OMPUntiedClause *) {} 6315 6316 void OMPClauseWriter::VisitOMPMergeableClause(OMPMergeableClause *) {} 6317 6318 void OMPClauseWriter::VisitOMPReadClause(OMPReadClause *) {} 6319 6320 void OMPClauseWriter::VisitOMPWriteClause(OMPWriteClause *) {} 6321 6322 void OMPClauseWriter::VisitOMPUpdateClause(OMPUpdateClause *C) { 6323 Record.push_back(C->isExtended() ? 1 : 0); 6324 if (C->isExtended()) { 6325 Record.AddSourceLocation(C->getLParenLoc()); 6326 Record.AddSourceLocation(C->getArgumentLoc()); 6327 Record.writeEnum(C->getDependencyKind()); 6328 } 6329 } 6330 6331 void OMPClauseWriter::VisitOMPCaptureClause(OMPCaptureClause *) {} 6332 6333 void OMPClauseWriter::VisitOMPCompareClause(OMPCompareClause *) {} 6334 6335 void OMPClauseWriter::VisitOMPSeqCstClause(OMPSeqCstClause *) {} 6336 6337 void OMPClauseWriter::VisitOMPAcqRelClause(OMPAcqRelClause *) {} 6338 6339 void OMPClauseWriter::VisitOMPAcquireClause(OMPAcquireClause *) {} 6340 6341 void OMPClauseWriter::VisitOMPReleaseClause(OMPReleaseClause *) {} 6342 6343 void OMPClauseWriter::VisitOMPRelaxedClause(OMPRelaxedClause *) {} 6344 6345 void OMPClauseWriter::VisitOMPThreadsClause(OMPThreadsClause *) {} 6346 6347 void OMPClauseWriter::VisitOMPSIMDClause(OMPSIMDClause *) {} 6348 6349 void OMPClauseWriter::VisitOMPNogroupClause(OMPNogroupClause *) {} 6350 6351 void OMPClauseWriter::VisitOMPInitClause(OMPInitClause *C) { 6352 Record.push_back(C->varlist_size()); 6353 for (Expr *VE : C->varlists()) 6354 Record.AddStmt(VE); 6355 Record.writeBool(C->getIsTarget()); 6356 Record.writeBool(C->getIsTargetSync()); 6357 Record.AddSourceLocation(C->getLParenLoc()); 6358 Record.AddSourceLocation(C->getVarLoc()); 6359 } 6360 6361 void OMPClauseWriter::VisitOMPUseClause(OMPUseClause *C) { 6362 Record.AddStmt(C->getInteropVar()); 6363 Record.AddSourceLocation(C->getLParenLoc()); 6364 Record.AddSourceLocation(C->getVarLoc()); 6365 } 6366 6367 void OMPClauseWriter::VisitOMPDestroyClause(OMPDestroyClause *C) { 6368 Record.AddStmt(C->getInteropVar()); 6369 Record.AddSourceLocation(C->getLParenLoc()); 6370 Record.AddSourceLocation(C->getVarLoc()); 6371 } 6372 6373 void OMPClauseWriter::VisitOMPNovariantsClause(OMPNovariantsClause *C) { 6374 VisitOMPClauseWithPreInit(C); 6375 Record.AddStmt(C->getCondition()); 6376 Record.AddSourceLocation(C->getLParenLoc()); 6377 } 6378 6379 void OMPClauseWriter::VisitOMPNocontextClause(OMPNocontextClause *C) { 6380 VisitOMPClauseWithPreInit(C); 6381 Record.AddStmt(C->getCondition()); 6382 Record.AddSourceLocation(C->getLParenLoc()); 6383 } 6384 6385 void OMPClauseWriter::VisitOMPFilterClause(OMPFilterClause *C) { 6386 VisitOMPClauseWithPreInit(C); 6387 Record.AddStmt(C->getThreadID()); 6388 Record.AddSourceLocation(C->getLParenLoc()); 6389 } 6390 6391 void OMPClauseWriter::VisitOMPAlignClause(OMPAlignClause *C) { 6392 Record.AddStmt(C->getAlignment()); 6393 Record.AddSourceLocation(C->getLParenLoc()); 6394 } 6395 6396 void OMPClauseWriter::VisitOMPPrivateClause(OMPPrivateClause *C) { 6397 Record.push_back(C->varlist_size()); 6398 Record.AddSourceLocation(C->getLParenLoc()); 6399 for (auto *VE : C->varlists()) { 6400 Record.AddStmt(VE); 6401 } 6402 for (auto *VE : C->private_copies()) { 6403 Record.AddStmt(VE); 6404 } 6405 } 6406 6407 void OMPClauseWriter::VisitOMPFirstprivateClause(OMPFirstprivateClause *C) { 6408 Record.push_back(C->varlist_size()); 6409 VisitOMPClauseWithPreInit(C); 6410 Record.AddSourceLocation(C->getLParenLoc()); 6411 for (auto *VE : C->varlists()) { 6412 Record.AddStmt(VE); 6413 } 6414 for (auto *VE : C->private_copies()) { 6415 Record.AddStmt(VE); 6416 } 6417 for (auto *VE : C->inits()) { 6418 Record.AddStmt(VE); 6419 } 6420 } 6421 6422 void OMPClauseWriter::VisitOMPLastprivateClause(OMPLastprivateClause *C) { 6423 Record.push_back(C->varlist_size()); 6424 VisitOMPClauseWithPostUpdate(C); 6425 Record.AddSourceLocation(C->getLParenLoc()); 6426 Record.writeEnum(C->getKind()); 6427 Record.AddSourceLocation(C->getKindLoc()); 6428 Record.AddSourceLocation(C->getColonLoc()); 6429 for (auto *VE : C->varlists()) 6430 Record.AddStmt(VE); 6431 for (auto *E : C->private_copies()) 6432 Record.AddStmt(E); 6433 for (auto *E : C->source_exprs()) 6434 Record.AddStmt(E); 6435 for (auto *E : C->destination_exprs()) 6436 Record.AddStmt(E); 6437 for (auto *E : C->assignment_ops()) 6438 Record.AddStmt(E); 6439 } 6440 6441 void OMPClauseWriter::VisitOMPSharedClause(OMPSharedClause *C) { 6442 Record.push_back(C->varlist_size()); 6443 Record.AddSourceLocation(C->getLParenLoc()); 6444 for (auto *VE : C->varlists()) 6445 Record.AddStmt(VE); 6446 } 6447 6448 void OMPClauseWriter::VisitOMPReductionClause(OMPReductionClause *C) { 6449 Record.push_back(C->varlist_size()); 6450 Record.writeEnum(C->getModifier()); 6451 VisitOMPClauseWithPostUpdate(C); 6452 Record.AddSourceLocation(C->getLParenLoc()); 6453 Record.AddSourceLocation(C->getModifierLoc()); 6454 Record.AddSourceLocation(C->getColonLoc()); 6455 Record.AddNestedNameSpecifierLoc(C->getQualifierLoc()); 6456 Record.AddDeclarationNameInfo(C->getNameInfo()); 6457 for (auto *VE : C->varlists()) 6458 Record.AddStmt(VE); 6459 for (auto *VE : C->privates()) 6460 Record.AddStmt(VE); 6461 for (auto *E : C->lhs_exprs()) 6462 Record.AddStmt(E); 6463 for (auto *E : C->rhs_exprs()) 6464 Record.AddStmt(E); 6465 for (auto *E : C->reduction_ops()) 6466 Record.AddStmt(E); 6467 if (C->getModifier() == clang::OMPC_REDUCTION_inscan) { 6468 for (auto *E : C->copy_ops()) 6469 Record.AddStmt(E); 6470 for (auto *E : C->copy_array_temps()) 6471 Record.AddStmt(E); 6472 for (auto *E : C->copy_array_elems()) 6473 Record.AddStmt(E); 6474 } 6475 } 6476 6477 void OMPClauseWriter::VisitOMPTaskReductionClause(OMPTaskReductionClause *C) { 6478 Record.push_back(C->varlist_size()); 6479 VisitOMPClauseWithPostUpdate(C); 6480 Record.AddSourceLocation(C->getLParenLoc()); 6481 Record.AddSourceLocation(C->getColonLoc()); 6482 Record.AddNestedNameSpecifierLoc(C->getQualifierLoc()); 6483 Record.AddDeclarationNameInfo(C->getNameInfo()); 6484 for (auto *VE : C->varlists()) 6485 Record.AddStmt(VE); 6486 for (auto *VE : C->privates()) 6487 Record.AddStmt(VE); 6488 for (auto *E : C->lhs_exprs()) 6489 Record.AddStmt(E); 6490 for (auto *E : C->rhs_exprs()) 6491 Record.AddStmt(E); 6492 for (auto *E : C->reduction_ops()) 6493 Record.AddStmt(E); 6494 } 6495 6496 void OMPClauseWriter::VisitOMPInReductionClause(OMPInReductionClause *C) { 6497 Record.push_back(C->varlist_size()); 6498 VisitOMPClauseWithPostUpdate(C); 6499 Record.AddSourceLocation(C->getLParenLoc()); 6500 Record.AddSourceLocation(C->getColonLoc()); 6501 Record.AddNestedNameSpecifierLoc(C->getQualifierLoc()); 6502 Record.AddDeclarationNameInfo(C->getNameInfo()); 6503 for (auto *VE : C->varlists()) 6504 Record.AddStmt(VE); 6505 for (auto *VE : C->privates()) 6506 Record.AddStmt(VE); 6507 for (auto *E : C->lhs_exprs()) 6508 Record.AddStmt(E); 6509 for (auto *E : C->rhs_exprs()) 6510 Record.AddStmt(E); 6511 for (auto *E : C->reduction_ops()) 6512 Record.AddStmt(E); 6513 for (auto *E : C->taskgroup_descriptors()) 6514 Record.AddStmt(E); 6515 } 6516 6517 void OMPClauseWriter::VisitOMPLinearClause(OMPLinearClause *C) { 6518 Record.push_back(C->varlist_size()); 6519 VisitOMPClauseWithPostUpdate(C); 6520 Record.AddSourceLocation(C->getLParenLoc()); 6521 Record.AddSourceLocation(C->getColonLoc()); 6522 Record.push_back(C->getModifier()); 6523 Record.AddSourceLocation(C->getModifierLoc()); 6524 for (auto *VE : C->varlists()) { 6525 Record.AddStmt(VE); 6526 } 6527 for (auto *VE : C->privates()) { 6528 Record.AddStmt(VE); 6529 } 6530 for (auto *VE : C->inits()) { 6531 Record.AddStmt(VE); 6532 } 6533 for (auto *VE : C->updates()) { 6534 Record.AddStmt(VE); 6535 } 6536 for (auto *VE : C->finals()) { 6537 Record.AddStmt(VE); 6538 } 6539 Record.AddStmt(C->getStep()); 6540 Record.AddStmt(C->getCalcStep()); 6541 for (auto *VE : C->used_expressions()) 6542 Record.AddStmt(VE); 6543 } 6544 6545 void OMPClauseWriter::VisitOMPAlignedClause(OMPAlignedClause *C) { 6546 Record.push_back(C->varlist_size()); 6547 Record.AddSourceLocation(C->getLParenLoc()); 6548 Record.AddSourceLocation(C->getColonLoc()); 6549 for (auto *VE : C->varlists()) 6550 Record.AddStmt(VE); 6551 Record.AddStmt(C->getAlignment()); 6552 } 6553 6554 void OMPClauseWriter::VisitOMPCopyinClause(OMPCopyinClause *C) { 6555 Record.push_back(C->varlist_size()); 6556 Record.AddSourceLocation(C->getLParenLoc()); 6557 for (auto *VE : C->varlists()) 6558 Record.AddStmt(VE); 6559 for (auto *E : C->source_exprs()) 6560 Record.AddStmt(E); 6561 for (auto *E : C->destination_exprs()) 6562 Record.AddStmt(E); 6563 for (auto *E : C->assignment_ops()) 6564 Record.AddStmt(E); 6565 } 6566 6567 void OMPClauseWriter::VisitOMPCopyprivateClause(OMPCopyprivateClause *C) { 6568 Record.push_back(C->varlist_size()); 6569 Record.AddSourceLocation(C->getLParenLoc()); 6570 for (auto *VE : C->varlists()) 6571 Record.AddStmt(VE); 6572 for (auto *E : C->source_exprs()) 6573 Record.AddStmt(E); 6574 for (auto *E : C->destination_exprs()) 6575 Record.AddStmt(E); 6576 for (auto *E : C->assignment_ops()) 6577 Record.AddStmt(E); 6578 } 6579 6580 void OMPClauseWriter::VisitOMPFlushClause(OMPFlushClause *C) { 6581 Record.push_back(C->varlist_size()); 6582 Record.AddSourceLocation(C->getLParenLoc()); 6583 for (auto *VE : C->varlists()) 6584 Record.AddStmt(VE); 6585 } 6586 6587 void OMPClauseWriter::VisitOMPDepobjClause(OMPDepobjClause *C) { 6588 Record.AddStmt(C->getDepobj()); 6589 Record.AddSourceLocation(C->getLParenLoc()); 6590 } 6591 6592 void OMPClauseWriter::VisitOMPDependClause(OMPDependClause *C) { 6593 Record.push_back(C->varlist_size()); 6594 Record.push_back(C->getNumLoops()); 6595 Record.AddSourceLocation(C->getLParenLoc()); 6596 Record.AddStmt(C->getModifier()); 6597 Record.push_back(C->getDependencyKind()); 6598 Record.AddSourceLocation(C->getDependencyLoc()); 6599 Record.AddSourceLocation(C->getColonLoc()); 6600 Record.AddSourceLocation(C->getOmpAllMemoryLoc()); 6601 for (auto *VE : C->varlists()) 6602 Record.AddStmt(VE); 6603 for (unsigned I = 0, E = C->getNumLoops(); I < E; ++I) 6604 Record.AddStmt(C->getLoopData(I)); 6605 } 6606 6607 void OMPClauseWriter::VisitOMPDeviceClause(OMPDeviceClause *C) { 6608 VisitOMPClauseWithPreInit(C); 6609 Record.writeEnum(C->getModifier()); 6610 Record.AddStmt(C->getDevice()); 6611 Record.AddSourceLocation(C->getModifierLoc()); 6612 Record.AddSourceLocation(C->getLParenLoc()); 6613 } 6614 6615 void OMPClauseWriter::VisitOMPMapClause(OMPMapClause *C) { 6616 Record.push_back(C->varlist_size()); 6617 Record.push_back(C->getUniqueDeclarationsNum()); 6618 Record.push_back(C->getTotalComponentListNum()); 6619 Record.push_back(C->getTotalComponentsNum()); 6620 Record.AddSourceLocation(C->getLParenLoc()); 6621 for (unsigned I = 0; I < NumberOfOMPMapClauseModifiers; ++I) { 6622 Record.push_back(C->getMapTypeModifier(I)); 6623 Record.AddSourceLocation(C->getMapTypeModifierLoc(I)); 6624 } 6625 Record.AddNestedNameSpecifierLoc(C->getMapperQualifierLoc()); 6626 Record.AddDeclarationNameInfo(C->getMapperIdInfo()); 6627 Record.push_back(C->getMapType()); 6628 Record.AddSourceLocation(C->getMapLoc()); 6629 Record.AddSourceLocation(C->getColonLoc()); 6630 for (auto *E : C->varlists()) 6631 Record.AddStmt(E); 6632 for (auto *E : C->mapperlists()) 6633 Record.AddStmt(E); 6634 for (auto *D : C->all_decls()) 6635 Record.AddDeclRef(D); 6636 for (auto N : C->all_num_lists()) 6637 Record.push_back(N); 6638 for (auto N : C->all_lists_sizes()) 6639 Record.push_back(N); 6640 for (auto &M : C->all_components()) { 6641 Record.AddStmt(M.getAssociatedExpression()); 6642 Record.AddDeclRef(M.getAssociatedDeclaration()); 6643 } 6644 } 6645 6646 void OMPClauseWriter::VisitOMPAllocateClause(OMPAllocateClause *C) { 6647 Record.push_back(C->varlist_size()); 6648 Record.AddSourceLocation(C->getLParenLoc()); 6649 Record.AddSourceLocation(C->getColonLoc()); 6650 Record.AddStmt(C->getAllocator()); 6651 for (auto *VE : C->varlists()) 6652 Record.AddStmt(VE); 6653 } 6654 6655 void OMPClauseWriter::VisitOMPNumTeamsClause(OMPNumTeamsClause *C) { 6656 VisitOMPClauseWithPreInit(C); 6657 Record.AddStmt(C->getNumTeams()); 6658 Record.AddSourceLocation(C->getLParenLoc()); 6659 } 6660 6661 void OMPClauseWriter::VisitOMPThreadLimitClause(OMPThreadLimitClause *C) { 6662 VisitOMPClauseWithPreInit(C); 6663 Record.AddStmt(C->getThreadLimit()); 6664 Record.AddSourceLocation(C->getLParenLoc()); 6665 } 6666 6667 void OMPClauseWriter::VisitOMPPriorityClause(OMPPriorityClause *C) { 6668 VisitOMPClauseWithPreInit(C); 6669 Record.AddStmt(C->getPriority()); 6670 Record.AddSourceLocation(C->getLParenLoc()); 6671 } 6672 6673 void OMPClauseWriter::VisitOMPGrainsizeClause(OMPGrainsizeClause *C) { 6674 VisitOMPClauseWithPreInit(C); 6675 Record.AddStmt(C->getGrainsize()); 6676 Record.AddSourceLocation(C->getLParenLoc()); 6677 } 6678 6679 void OMPClauseWriter::VisitOMPNumTasksClause(OMPNumTasksClause *C) { 6680 VisitOMPClauseWithPreInit(C); 6681 Record.AddStmt(C->getNumTasks()); 6682 Record.AddSourceLocation(C->getLParenLoc()); 6683 } 6684 6685 void OMPClauseWriter::VisitOMPHintClause(OMPHintClause *C) { 6686 Record.AddStmt(C->getHint()); 6687 Record.AddSourceLocation(C->getLParenLoc()); 6688 } 6689 6690 void OMPClauseWriter::VisitOMPDistScheduleClause(OMPDistScheduleClause *C) { 6691 VisitOMPClauseWithPreInit(C); 6692 Record.push_back(C->getDistScheduleKind()); 6693 Record.AddStmt(C->getChunkSize()); 6694 Record.AddSourceLocation(C->getLParenLoc()); 6695 Record.AddSourceLocation(C->getDistScheduleKindLoc()); 6696 Record.AddSourceLocation(C->getCommaLoc()); 6697 } 6698 6699 void OMPClauseWriter::VisitOMPDefaultmapClause(OMPDefaultmapClause *C) { 6700 Record.push_back(C->getDefaultmapKind()); 6701 Record.push_back(C->getDefaultmapModifier()); 6702 Record.AddSourceLocation(C->getLParenLoc()); 6703 Record.AddSourceLocation(C->getDefaultmapModifierLoc()); 6704 Record.AddSourceLocation(C->getDefaultmapKindLoc()); 6705 } 6706 6707 void OMPClauseWriter::VisitOMPToClause(OMPToClause *C) { 6708 Record.push_back(C->varlist_size()); 6709 Record.push_back(C->getUniqueDeclarationsNum()); 6710 Record.push_back(C->getTotalComponentListNum()); 6711 Record.push_back(C->getTotalComponentsNum()); 6712 Record.AddSourceLocation(C->getLParenLoc()); 6713 for (unsigned I = 0; I < NumberOfOMPMotionModifiers; ++I) { 6714 Record.push_back(C->getMotionModifier(I)); 6715 Record.AddSourceLocation(C->getMotionModifierLoc(I)); 6716 } 6717 Record.AddNestedNameSpecifierLoc(C->getMapperQualifierLoc()); 6718 Record.AddDeclarationNameInfo(C->getMapperIdInfo()); 6719 Record.AddSourceLocation(C->getColonLoc()); 6720 for (auto *E : C->varlists()) 6721 Record.AddStmt(E); 6722 for (auto *E : C->mapperlists()) 6723 Record.AddStmt(E); 6724 for (auto *D : C->all_decls()) 6725 Record.AddDeclRef(D); 6726 for (auto N : C->all_num_lists()) 6727 Record.push_back(N); 6728 for (auto N : C->all_lists_sizes()) 6729 Record.push_back(N); 6730 for (auto &M : C->all_components()) { 6731 Record.AddStmt(M.getAssociatedExpression()); 6732 Record.writeBool(M.isNonContiguous()); 6733 Record.AddDeclRef(M.getAssociatedDeclaration()); 6734 } 6735 } 6736 6737 void OMPClauseWriter::VisitOMPFromClause(OMPFromClause *C) { 6738 Record.push_back(C->varlist_size()); 6739 Record.push_back(C->getUniqueDeclarationsNum()); 6740 Record.push_back(C->getTotalComponentListNum()); 6741 Record.push_back(C->getTotalComponentsNum()); 6742 Record.AddSourceLocation(C->getLParenLoc()); 6743 for (unsigned I = 0; I < NumberOfOMPMotionModifiers; ++I) { 6744 Record.push_back(C->getMotionModifier(I)); 6745 Record.AddSourceLocation(C->getMotionModifierLoc(I)); 6746 } 6747 Record.AddNestedNameSpecifierLoc(C->getMapperQualifierLoc()); 6748 Record.AddDeclarationNameInfo(C->getMapperIdInfo()); 6749 Record.AddSourceLocation(C->getColonLoc()); 6750 for (auto *E : C->varlists()) 6751 Record.AddStmt(E); 6752 for (auto *E : C->mapperlists()) 6753 Record.AddStmt(E); 6754 for (auto *D : C->all_decls()) 6755 Record.AddDeclRef(D); 6756 for (auto N : C->all_num_lists()) 6757 Record.push_back(N); 6758 for (auto N : C->all_lists_sizes()) 6759 Record.push_back(N); 6760 for (auto &M : C->all_components()) { 6761 Record.AddStmt(M.getAssociatedExpression()); 6762 Record.writeBool(M.isNonContiguous()); 6763 Record.AddDeclRef(M.getAssociatedDeclaration()); 6764 } 6765 } 6766 6767 void OMPClauseWriter::VisitOMPUseDevicePtrClause(OMPUseDevicePtrClause *C) { 6768 Record.push_back(C->varlist_size()); 6769 Record.push_back(C->getUniqueDeclarationsNum()); 6770 Record.push_back(C->getTotalComponentListNum()); 6771 Record.push_back(C->getTotalComponentsNum()); 6772 Record.AddSourceLocation(C->getLParenLoc()); 6773 for (auto *E : C->varlists()) 6774 Record.AddStmt(E); 6775 for (auto *VE : C->private_copies()) 6776 Record.AddStmt(VE); 6777 for (auto *VE : C->inits()) 6778 Record.AddStmt(VE); 6779 for (auto *D : C->all_decls()) 6780 Record.AddDeclRef(D); 6781 for (auto N : C->all_num_lists()) 6782 Record.push_back(N); 6783 for (auto N : C->all_lists_sizes()) 6784 Record.push_back(N); 6785 for (auto &M : C->all_components()) { 6786 Record.AddStmt(M.getAssociatedExpression()); 6787 Record.AddDeclRef(M.getAssociatedDeclaration()); 6788 } 6789 } 6790 6791 void OMPClauseWriter::VisitOMPUseDeviceAddrClause(OMPUseDeviceAddrClause *C) { 6792 Record.push_back(C->varlist_size()); 6793 Record.push_back(C->getUniqueDeclarationsNum()); 6794 Record.push_back(C->getTotalComponentListNum()); 6795 Record.push_back(C->getTotalComponentsNum()); 6796 Record.AddSourceLocation(C->getLParenLoc()); 6797 for (auto *E : C->varlists()) 6798 Record.AddStmt(E); 6799 for (auto *D : C->all_decls()) 6800 Record.AddDeclRef(D); 6801 for (auto N : C->all_num_lists()) 6802 Record.push_back(N); 6803 for (auto N : C->all_lists_sizes()) 6804 Record.push_back(N); 6805 for (auto &M : C->all_components()) { 6806 Record.AddStmt(M.getAssociatedExpression()); 6807 Record.AddDeclRef(M.getAssociatedDeclaration()); 6808 } 6809 } 6810 6811 void OMPClauseWriter::VisitOMPIsDevicePtrClause(OMPIsDevicePtrClause *C) { 6812 Record.push_back(C->varlist_size()); 6813 Record.push_back(C->getUniqueDeclarationsNum()); 6814 Record.push_back(C->getTotalComponentListNum()); 6815 Record.push_back(C->getTotalComponentsNum()); 6816 Record.AddSourceLocation(C->getLParenLoc()); 6817 for (auto *E : C->varlists()) 6818 Record.AddStmt(E); 6819 for (auto *D : C->all_decls()) 6820 Record.AddDeclRef(D); 6821 for (auto N : C->all_num_lists()) 6822 Record.push_back(N); 6823 for (auto N : C->all_lists_sizes()) 6824 Record.push_back(N); 6825 for (auto &M : C->all_components()) { 6826 Record.AddStmt(M.getAssociatedExpression()); 6827 Record.AddDeclRef(M.getAssociatedDeclaration()); 6828 } 6829 } 6830 6831 void OMPClauseWriter::VisitOMPHasDeviceAddrClause(OMPHasDeviceAddrClause *C) { 6832 Record.push_back(C->varlist_size()); 6833 Record.push_back(C->getUniqueDeclarationsNum()); 6834 Record.push_back(C->getTotalComponentListNum()); 6835 Record.push_back(C->getTotalComponentsNum()); 6836 Record.AddSourceLocation(C->getLParenLoc()); 6837 for (auto *E : C->varlists()) 6838 Record.AddStmt(E); 6839 for (auto *D : C->all_decls()) 6840 Record.AddDeclRef(D); 6841 for (auto N : C->all_num_lists()) 6842 Record.push_back(N); 6843 for (auto N : C->all_lists_sizes()) 6844 Record.push_back(N); 6845 for (auto &M : C->all_components()) { 6846 Record.AddStmt(M.getAssociatedExpression()); 6847 Record.AddDeclRef(M.getAssociatedDeclaration()); 6848 } 6849 } 6850 6851 void OMPClauseWriter::VisitOMPUnifiedAddressClause(OMPUnifiedAddressClause *) {} 6852 6853 void OMPClauseWriter::VisitOMPUnifiedSharedMemoryClause( 6854 OMPUnifiedSharedMemoryClause *) {} 6855 6856 void OMPClauseWriter::VisitOMPReverseOffloadClause(OMPReverseOffloadClause *) {} 6857 6858 void 6859 OMPClauseWriter::VisitOMPDynamicAllocatorsClause(OMPDynamicAllocatorsClause *) { 6860 } 6861 6862 void OMPClauseWriter::VisitOMPAtomicDefaultMemOrderClause( 6863 OMPAtomicDefaultMemOrderClause *C) { 6864 Record.push_back(C->getAtomicDefaultMemOrderKind()); 6865 Record.AddSourceLocation(C->getLParenLoc()); 6866 Record.AddSourceLocation(C->getAtomicDefaultMemOrderKindKwLoc()); 6867 } 6868 6869 void OMPClauseWriter::VisitOMPNontemporalClause(OMPNontemporalClause *C) { 6870 Record.push_back(C->varlist_size()); 6871 Record.AddSourceLocation(C->getLParenLoc()); 6872 for (auto *VE : C->varlists()) 6873 Record.AddStmt(VE); 6874 for (auto *E : C->private_refs()) 6875 Record.AddStmt(E); 6876 } 6877 6878 void OMPClauseWriter::VisitOMPInclusiveClause(OMPInclusiveClause *C) { 6879 Record.push_back(C->varlist_size()); 6880 Record.AddSourceLocation(C->getLParenLoc()); 6881 for (auto *VE : C->varlists()) 6882 Record.AddStmt(VE); 6883 } 6884 6885 void OMPClauseWriter::VisitOMPExclusiveClause(OMPExclusiveClause *C) { 6886 Record.push_back(C->varlist_size()); 6887 Record.AddSourceLocation(C->getLParenLoc()); 6888 for (auto *VE : C->varlists()) 6889 Record.AddStmt(VE); 6890 } 6891 6892 void OMPClauseWriter::VisitOMPOrderClause(OMPOrderClause *C) { 6893 Record.writeEnum(C->getKind()); 6894 Record.AddSourceLocation(C->getLParenLoc()); 6895 Record.AddSourceLocation(C->getKindKwLoc()); 6896 } 6897 6898 void OMPClauseWriter::VisitOMPUsesAllocatorsClause(OMPUsesAllocatorsClause *C) { 6899 Record.push_back(C->getNumberOfAllocators()); 6900 Record.AddSourceLocation(C->getLParenLoc()); 6901 for (unsigned I = 0, E = C->getNumberOfAllocators(); I < E; ++I) { 6902 OMPUsesAllocatorsClause::Data Data = C->getAllocatorData(I); 6903 Record.AddStmt(Data.Allocator); 6904 Record.AddStmt(Data.AllocatorTraits); 6905 Record.AddSourceLocation(Data.LParenLoc); 6906 Record.AddSourceLocation(Data.RParenLoc); 6907 } 6908 } 6909 6910 void OMPClauseWriter::VisitOMPAffinityClause(OMPAffinityClause *C) { 6911 Record.push_back(C->varlist_size()); 6912 Record.AddSourceLocation(C->getLParenLoc()); 6913 Record.AddStmt(C->getModifier()); 6914 Record.AddSourceLocation(C->getColonLoc()); 6915 for (Expr *E : C->varlists()) 6916 Record.AddStmt(E); 6917 } 6918 6919 void OMPClauseWriter::VisitOMPBindClause(OMPBindClause *C) { 6920 Record.writeEnum(C->getBindKind()); 6921 Record.AddSourceLocation(C->getLParenLoc()); 6922 Record.AddSourceLocation(C->getBindKindLoc()); 6923 } 6924 6925 void ASTRecordWriter::writeOMPTraitInfo(const OMPTraitInfo *TI) { 6926 writeUInt32(TI->Sets.size()); 6927 for (const auto &Set : TI->Sets) { 6928 writeEnum(Set.Kind); 6929 writeUInt32(Set.Selectors.size()); 6930 for (const auto &Selector : Set.Selectors) { 6931 writeEnum(Selector.Kind); 6932 writeBool(Selector.ScoreOrCondition); 6933 if (Selector.ScoreOrCondition) 6934 writeExprRef(Selector.ScoreOrCondition); 6935 writeUInt32(Selector.Properties.size()); 6936 for (const auto &Property : Selector.Properties) 6937 writeEnum(Property.Kind); 6938 } 6939 } 6940 } 6941 6942 void ASTRecordWriter::writeOMPChildren(OMPChildren *Data) { 6943 if (!Data) 6944 return; 6945 writeUInt32(Data->getNumClauses()); 6946 writeUInt32(Data->getNumChildren()); 6947 writeBool(Data->hasAssociatedStmt()); 6948 for (unsigned I = 0, E = Data->getNumClauses(); I < E; ++I) 6949 writeOMPClause(Data->getClauses()[I]); 6950 if (Data->hasAssociatedStmt()) 6951 AddStmt(Data->getAssociatedStmt()); 6952 for (unsigned I = 0, E = Data->getNumChildren(); I < E; ++I) 6953 AddStmt(Data->getChildren()[I]); 6954 } 6955