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 if (!A) 4351 return Record.push_back(0); 4352 Record.push_back(A->getKind() + 1); // FIXME: stable encoding, target attrs 4353 4354 Record.AddIdentifierRef(A->getAttrName()); 4355 Record.AddIdentifierRef(A->getScopeName()); 4356 Record.AddSourceRange(A->getRange()); 4357 Record.AddSourceLocation(A->getScopeLoc()); 4358 Record.push_back(A->getParsedKind()); 4359 Record.push_back(A->getSyntax()); 4360 Record.push_back(A->getAttributeSpellingListIndexRaw()); 4361 4362 #include "clang/Serialization/AttrPCHWrite.inc" 4363 } 4364 4365 /// Emit the list of attributes to the specified record. 4366 void ASTRecordWriter::AddAttributes(ArrayRef<const Attr *> Attrs) { 4367 push_back(Attrs.size()); 4368 for (const auto *A : Attrs) 4369 AddAttr(A); 4370 } 4371 4372 void ASTWriter::AddToken(const Token &Tok, RecordDataImpl &Record) { 4373 AddSourceLocation(Tok.getLocation(), Record); 4374 Record.push_back(Tok.getLength()); 4375 4376 // FIXME: When reading literal tokens, reconstruct the literal pointer 4377 // if it is needed. 4378 AddIdentifierRef(Tok.getIdentifierInfo(), Record); 4379 // FIXME: Should translate token kind to a stable encoding. 4380 Record.push_back(Tok.getKind()); 4381 // FIXME: Should translate token flags to a stable encoding. 4382 Record.push_back(Tok.getFlags()); 4383 } 4384 4385 void ASTWriter::AddString(StringRef Str, RecordDataImpl &Record) { 4386 Record.push_back(Str.size()); 4387 Record.insert(Record.end(), Str.begin(), Str.end()); 4388 } 4389 4390 bool ASTWriter::PreparePathForOutput(SmallVectorImpl<char> &Path) { 4391 assert(Context && "should have context when outputting path"); 4392 4393 bool Changed = 4394 cleanPathForOutput(Context->getSourceManager().getFileManager(), Path); 4395 4396 // Remove a prefix to make the path relative, if relevant. 4397 const char *PathBegin = Path.data(); 4398 const char *PathPtr = 4399 adjustFilenameForRelocatableAST(PathBegin, BaseDirectory); 4400 if (PathPtr != PathBegin) { 4401 Path.erase(Path.begin(), Path.begin() + (PathPtr - PathBegin)); 4402 Changed = true; 4403 } 4404 4405 return Changed; 4406 } 4407 4408 void ASTWriter::AddPath(StringRef Path, RecordDataImpl &Record) { 4409 SmallString<128> FilePath(Path); 4410 PreparePathForOutput(FilePath); 4411 AddString(FilePath, Record); 4412 } 4413 4414 void ASTWriter::EmitRecordWithPath(unsigned Abbrev, RecordDataRef Record, 4415 StringRef Path) { 4416 SmallString<128> FilePath(Path); 4417 PreparePathForOutput(FilePath); 4418 Stream.EmitRecordWithBlob(Abbrev, Record, FilePath); 4419 } 4420 4421 void ASTWriter::AddVersionTuple(const VersionTuple &Version, 4422 RecordDataImpl &Record) { 4423 Record.push_back(Version.getMajor()); 4424 if (Optional<unsigned> Minor = Version.getMinor()) 4425 Record.push_back(*Minor + 1); 4426 else 4427 Record.push_back(0); 4428 if (Optional<unsigned> Subminor = Version.getSubminor()) 4429 Record.push_back(*Subminor + 1); 4430 else 4431 Record.push_back(0); 4432 } 4433 4434 /// Note that the identifier II occurs at the given offset 4435 /// within the identifier table. 4436 void ASTWriter::SetIdentifierOffset(const IdentifierInfo *II, uint32_t Offset) { 4437 IdentID ID = IdentifierIDs[II]; 4438 // Only store offsets new to this AST file. Other identifier names are looked 4439 // up earlier in the chain and thus don't need an offset. 4440 if (ID >= FirstIdentID) 4441 IdentifierOffsets[ID - FirstIdentID] = Offset; 4442 } 4443 4444 /// Note that the selector Sel occurs at the given offset 4445 /// within the method pool/selector table. 4446 void ASTWriter::SetSelectorOffset(Selector Sel, uint32_t Offset) { 4447 unsigned ID = SelectorIDs[Sel]; 4448 assert(ID && "Unknown selector"); 4449 // Don't record offsets for selectors that are also available in a different 4450 // file. 4451 if (ID < FirstSelectorID) 4452 return; 4453 SelectorOffsets[ID - FirstSelectorID] = Offset; 4454 } 4455 4456 ASTWriter::ASTWriter(llvm::BitstreamWriter &Stream, 4457 SmallVectorImpl<char> &Buffer, 4458 InMemoryModuleCache &ModuleCache, 4459 ArrayRef<std::shared_ptr<ModuleFileExtension>> Extensions, 4460 bool IncludeTimestamps) 4461 : Stream(Stream), Buffer(Buffer), ModuleCache(ModuleCache), 4462 IncludeTimestamps(IncludeTimestamps) { 4463 for (const auto &Ext : Extensions) { 4464 if (auto Writer = Ext->createExtensionWriter(*this)) 4465 ModuleFileExtensionWriters.push_back(std::move(Writer)); 4466 } 4467 } 4468 4469 ASTWriter::~ASTWriter() = default; 4470 4471 const LangOptions &ASTWriter::getLangOpts() const { 4472 assert(WritingAST && "can't determine lang opts when not writing AST"); 4473 return Context->getLangOpts(); 4474 } 4475 4476 time_t ASTWriter::getTimestampForOutput(const FileEntry *E) const { 4477 return IncludeTimestamps ? E->getModificationTime() : 0; 4478 } 4479 4480 ASTFileSignature ASTWriter::WriteAST(Sema &SemaRef, 4481 const std::string &OutputFile, 4482 Module *WritingModule, StringRef isysroot, 4483 bool hasErrors, 4484 bool ShouldCacheASTInMemory) { 4485 WritingAST = true; 4486 4487 ASTHasCompilerErrors = hasErrors; 4488 4489 // Emit the file header. 4490 Stream.Emit((unsigned)'C', 8); 4491 Stream.Emit((unsigned)'P', 8); 4492 Stream.Emit((unsigned)'C', 8); 4493 Stream.Emit((unsigned)'H', 8); 4494 4495 WriteBlockInfoBlock(); 4496 4497 Context = &SemaRef.Context; 4498 PP = &SemaRef.PP; 4499 this->WritingModule = WritingModule; 4500 ASTFileSignature Signature = 4501 WriteASTCore(SemaRef, isysroot, OutputFile, WritingModule); 4502 Context = nullptr; 4503 PP = nullptr; 4504 this->WritingModule = nullptr; 4505 this->BaseDirectory.clear(); 4506 4507 WritingAST = false; 4508 if (ShouldCacheASTInMemory) { 4509 // Construct MemoryBuffer and update buffer manager. 4510 ModuleCache.addBuiltPCM(OutputFile, 4511 llvm::MemoryBuffer::getMemBufferCopy( 4512 StringRef(Buffer.begin(), Buffer.size()))); 4513 } 4514 return Signature; 4515 } 4516 4517 template<typename Vector> 4518 static void AddLazyVectorDecls(ASTWriter &Writer, Vector &Vec, 4519 ASTWriter::RecordData &Record) { 4520 for (typename Vector::iterator I = Vec.begin(nullptr, true), E = Vec.end(); 4521 I != E; ++I) { 4522 Writer.AddDeclRef(*I, Record); 4523 } 4524 } 4525 4526 ASTFileSignature ASTWriter::WriteASTCore(Sema &SemaRef, StringRef isysroot, 4527 const std::string &OutputFile, 4528 Module *WritingModule) { 4529 using namespace llvm; 4530 4531 bool isModule = WritingModule != nullptr; 4532 4533 // Make sure that the AST reader knows to finalize itself. 4534 if (Chain) 4535 Chain->finalizeForWriting(); 4536 4537 ASTContext &Context = SemaRef.Context; 4538 Preprocessor &PP = SemaRef.PP; 4539 4540 // Set up predefined declaration IDs. 4541 auto RegisterPredefDecl = [&] (Decl *D, PredefinedDeclIDs ID) { 4542 if (D) { 4543 assert(D->isCanonicalDecl() && "predefined decl is not canonical"); 4544 DeclIDs[D] = ID; 4545 } 4546 }; 4547 RegisterPredefDecl(Context.getTranslationUnitDecl(), 4548 PREDEF_DECL_TRANSLATION_UNIT_ID); 4549 RegisterPredefDecl(Context.ObjCIdDecl, PREDEF_DECL_OBJC_ID_ID); 4550 RegisterPredefDecl(Context.ObjCSelDecl, PREDEF_DECL_OBJC_SEL_ID); 4551 RegisterPredefDecl(Context.ObjCClassDecl, PREDEF_DECL_OBJC_CLASS_ID); 4552 RegisterPredefDecl(Context.ObjCProtocolClassDecl, 4553 PREDEF_DECL_OBJC_PROTOCOL_ID); 4554 RegisterPredefDecl(Context.Int128Decl, PREDEF_DECL_INT_128_ID); 4555 RegisterPredefDecl(Context.UInt128Decl, PREDEF_DECL_UNSIGNED_INT_128_ID); 4556 RegisterPredefDecl(Context.ObjCInstanceTypeDecl, 4557 PREDEF_DECL_OBJC_INSTANCETYPE_ID); 4558 RegisterPredefDecl(Context.BuiltinVaListDecl, PREDEF_DECL_BUILTIN_VA_LIST_ID); 4559 RegisterPredefDecl(Context.VaListTagDecl, PREDEF_DECL_VA_LIST_TAG); 4560 RegisterPredefDecl(Context.BuiltinMSVaListDecl, 4561 PREDEF_DECL_BUILTIN_MS_VA_LIST_ID); 4562 RegisterPredefDecl(Context.MSGuidTagDecl, 4563 PREDEF_DECL_BUILTIN_MS_GUID_ID); 4564 RegisterPredefDecl(Context.ExternCContext, PREDEF_DECL_EXTERN_C_CONTEXT_ID); 4565 RegisterPredefDecl(Context.MakeIntegerSeqDecl, 4566 PREDEF_DECL_MAKE_INTEGER_SEQ_ID); 4567 RegisterPredefDecl(Context.CFConstantStringTypeDecl, 4568 PREDEF_DECL_CF_CONSTANT_STRING_ID); 4569 RegisterPredefDecl(Context.CFConstantStringTagDecl, 4570 PREDEF_DECL_CF_CONSTANT_STRING_TAG_ID); 4571 RegisterPredefDecl(Context.TypePackElementDecl, 4572 PREDEF_DECL_TYPE_PACK_ELEMENT_ID); 4573 4574 // Build a record containing all of the tentative definitions in this file, in 4575 // TentativeDefinitions order. Generally, this record will be empty for 4576 // headers. 4577 RecordData TentativeDefinitions; 4578 AddLazyVectorDecls(*this, SemaRef.TentativeDefinitions, TentativeDefinitions); 4579 4580 // Build a record containing all of the file scoped decls in this file. 4581 RecordData UnusedFileScopedDecls; 4582 if (!isModule) 4583 AddLazyVectorDecls(*this, SemaRef.UnusedFileScopedDecls, 4584 UnusedFileScopedDecls); 4585 4586 // Build a record containing all of the delegating constructors we still need 4587 // to resolve. 4588 RecordData DelegatingCtorDecls; 4589 if (!isModule) 4590 AddLazyVectorDecls(*this, SemaRef.DelegatingCtorDecls, DelegatingCtorDecls); 4591 4592 // Write the set of weak, undeclared identifiers. We always write the 4593 // entire table, since later PCH files in a PCH chain are only interested in 4594 // the results at the end of the chain. 4595 RecordData WeakUndeclaredIdentifiers; 4596 for (const auto &WeakUndeclaredIdentifierList : 4597 SemaRef.WeakUndeclaredIdentifiers) { 4598 const IdentifierInfo *const II = WeakUndeclaredIdentifierList.first; 4599 for (const auto &WI : WeakUndeclaredIdentifierList.second) { 4600 AddIdentifierRef(II, WeakUndeclaredIdentifiers); 4601 AddIdentifierRef(WI.getAlias(), WeakUndeclaredIdentifiers); 4602 AddSourceLocation(WI.getLocation(), WeakUndeclaredIdentifiers); 4603 } 4604 } 4605 4606 // Build a record containing all of the ext_vector declarations. 4607 RecordData ExtVectorDecls; 4608 AddLazyVectorDecls(*this, SemaRef.ExtVectorDecls, ExtVectorDecls); 4609 4610 // Build a record containing all of the VTable uses information. 4611 RecordData VTableUses; 4612 if (!SemaRef.VTableUses.empty()) { 4613 for (unsigned I = 0, N = SemaRef.VTableUses.size(); I != N; ++I) { 4614 AddDeclRef(SemaRef.VTableUses[I].first, VTableUses); 4615 AddSourceLocation(SemaRef.VTableUses[I].second, VTableUses); 4616 VTableUses.push_back(SemaRef.VTablesUsed[SemaRef.VTableUses[I].first]); 4617 } 4618 } 4619 4620 // Build a record containing all of the UnusedLocalTypedefNameCandidates. 4621 RecordData UnusedLocalTypedefNameCandidates; 4622 for (const TypedefNameDecl *TD : SemaRef.UnusedLocalTypedefNameCandidates) 4623 AddDeclRef(TD, UnusedLocalTypedefNameCandidates); 4624 4625 // Build a record containing all of pending implicit instantiations. 4626 RecordData PendingInstantiations; 4627 for (const auto &I : SemaRef.PendingInstantiations) { 4628 AddDeclRef(I.first, PendingInstantiations); 4629 AddSourceLocation(I.second, PendingInstantiations); 4630 } 4631 assert(SemaRef.PendingLocalImplicitInstantiations.empty() && 4632 "There are local ones at end of translation unit!"); 4633 4634 // Build a record containing some declaration references. 4635 RecordData SemaDeclRefs; 4636 if (SemaRef.StdNamespace || SemaRef.StdBadAlloc || SemaRef.StdAlignValT) { 4637 AddDeclRef(SemaRef.getStdNamespace(), SemaDeclRefs); 4638 AddDeclRef(SemaRef.getStdBadAlloc(), SemaDeclRefs); 4639 AddDeclRef(SemaRef.getStdAlignValT(), SemaDeclRefs); 4640 } 4641 4642 RecordData CUDASpecialDeclRefs; 4643 if (Context.getcudaConfigureCallDecl()) { 4644 AddDeclRef(Context.getcudaConfigureCallDecl(), CUDASpecialDeclRefs); 4645 } 4646 4647 // Build a record containing all of the known namespaces. 4648 RecordData KnownNamespaces; 4649 for (const auto &I : SemaRef.KnownNamespaces) { 4650 if (!I.second) 4651 AddDeclRef(I.first, KnownNamespaces); 4652 } 4653 4654 // Build a record of all used, undefined objects that require definitions. 4655 RecordData UndefinedButUsed; 4656 4657 SmallVector<std::pair<NamedDecl *, SourceLocation>, 16> Undefined; 4658 SemaRef.getUndefinedButUsed(Undefined); 4659 for (const auto &I : Undefined) { 4660 AddDeclRef(I.first, UndefinedButUsed); 4661 AddSourceLocation(I.second, UndefinedButUsed); 4662 } 4663 4664 // Build a record containing all delete-expressions that we would like to 4665 // analyze later in AST. 4666 RecordData DeleteExprsToAnalyze; 4667 4668 if (!isModule) { 4669 for (const auto &DeleteExprsInfo : 4670 SemaRef.getMismatchingDeleteExpressions()) { 4671 AddDeclRef(DeleteExprsInfo.first, DeleteExprsToAnalyze); 4672 DeleteExprsToAnalyze.push_back(DeleteExprsInfo.second.size()); 4673 for (const auto &DeleteLoc : DeleteExprsInfo.second) { 4674 AddSourceLocation(DeleteLoc.first, DeleteExprsToAnalyze); 4675 DeleteExprsToAnalyze.push_back(DeleteLoc.second); 4676 } 4677 } 4678 } 4679 4680 // Write the control block 4681 WriteControlBlock(PP, Context, isysroot, OutputFile); 4682 4683 // Write the remaining AST contents. 4684 Stream.FlushToWord(); 4685 ASTBlockRange.first = Stream.GetCurrentBitNo(); 4686 Stream.EnterSubblock(AST_BLOCK_ID, 5); 4687 ASTBlockStartOffset = Stream.GetCurrentBitNo(); 4688 4689 // This is so that older clang versions, before the introduction 4690 // of the control block, can read and reject the newer PCH format. 4691 { 4692 RecordData Record = {VERSION_MAJOR}; 4693 Stream.EmitRecord(METADATA_OLD_FORMAT, Record); 4694 } 4695 4696 // Create a lexical update block containing all of the declarations in the 4697 // translation unit that do not come from other AST files. 4698 const TranslationUnitDecl *TU = Context.getTranslationUnitDecl(); 4699 SmallVector<uint32_t, 128> NewGlobalKindDeclPairs; 4700 for (const auto *D : TU->noload_decls()) { 4701 if (!D->isFromASTFile()) { 4702 NewGlobalKindDeclPairs.push_back(D->getKind()); 4703 NewGlobalKindDeclPairs.push_back(GetDeclRef(D)); 4704 } 4705 } 4706 4707 auto Abv = std::make_shared<BitCodeAbbrev>(); 4708 Abv->Add(llvm::BitCodeAbbrevOp(TU_UPDATE_LEXICAL)); 4709 Abv->Add(llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::Blob)); 4710 unsigned TuUpdateLexicalAbbrev = Stream.EmitAbbrev(std::move(Abv)); 4711 { 4712 RecordData::value_type Record[] = {TU_UPDATE_LEXICAL}; 4713 Stream.EmitRecordWithBlob(TuUpdateLexicalAbbrev, Record, 4714 bytes(NewGlobalKindDeclPairs)); 4715 } 4716 4717 // And a visible updates block for the translation unit. 4718 Abv = std::make_shared<BitCodeAbbrev>(); 4719 Abv->Add(llvm::BitCodeAbbrevOp(UPDATE_VISIBLE)); 4720 Abv->Add(llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::VBR, 6)); 4721 Abv->Add(llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::Blob)); 4722 UpdateVisibleAbbrev = Stream.EmitAbbrev(std::move(Abv)); 4723 WriteDeclContextVisibleUpdate(TU); 4724 4725 // If we have any extern "C" names, write out a visible update for them. 4726 if (Context.ExternCContext) 4727 WriteDeclContextVisibleUpdate(Context.ExternCContext); 4728 4729 // If the translation unit has an anonymous namespace, and we don't already 4730 // have an update block for it, write it as an update block. 4731 // FIXME: Why do we not do this if there's already an update block? 4732 if (NamespaceDecl *NS = TU->getAnonymousNamespace()) { 4733 ASTWriter::UpdateRecord &Record = DeclUpdates[TU]; 4734 if (Record.empty()) 4735 Record.push_back(DeclUpdate(UPD_CXX_ADDED_ANONYMOUS_NAMESPACE, NS)); 4736 } 4737 4738 // Add update records for all mangling numbers and static local numbers. 4739 // These aren't really update records, but this is a convenient way of 4740 // tagging this rare extra data onto the declarations. 4741 for (const auto &Number : Context.MangleNumbers) 4742 if (!Number.first->isFromASTFile()) 4743 DeclUpdates[Number.first].push_back(DeclUpdate(UPD_MANGLING_NUMBER, 4744 Number.second)); 4745 for (const auto &Number : Context.StaticLocalNumbers) 4746 if (!Number.first->isFromASTFile()) 4747 DeclUpdates[Number.first].push_back(DeclUpdate(UPD_STATIC_LOCAL_NUMBER, 4748 Number.second)); 4749 4750 // Make sure visible decls, added to DeclContexts previously loaded from 4751 // an AST file, are registered for serialization. Likewise for template 4752 // specializations added to imported templates. 4753 for (const auto *I : DeclsToEmitEvenIfUnreferenced) { 4754 GetDeclRef(I); 4755 } 4756 4757 // Make sure all decls associated with an identifier are registered for 4758 // serialization, if we're storing decls with identifiers. 4759 if (!WritingModule || !getLangOpts().CPlusPlus) { 4760 llvm::SmallVector<const IdentifierInfo*, 256> IIs; 4761 for (const auto &ID : PP.getIdentifierTable()) { 4762 const IdentifierInfo *II = ID.second; 4763 if (!Chain || !II->isFromAST() || II->hasChangedSinceDeserialization()) 4764 IIs.push_back(II); 4765 } 4766 // Sort the identifiers to visit based on their name. 4767 llvm::sort(IIs, llvm::deref<std::less<>>()); 4768 for (const IdentifierInfo *II : IIs) { 4769 for (IdentifierResolver::iterator D = SemaRef.IdResolver.begin(II), 4770 DEnd = SemaRef.IdResolver.end(); 4771 D != DEnd; ++D) { 4772 GetDeclRef(*D); 4773 } 4774 } 4775 } 4776 4777 // For method pool in the module, if it contains an entry for a selector, 4778 // the entry should be complete, containing everything introduced by that 4779 // module and all modules it imports. It's possible that the entry is out of 4780 // date, so we need to pull in the new content here. 4781 4782 // It's possible that updateOutOfDateSelector can update SelectorIDs. To be 4783 // safe, we copy all selectors out. 4784 llvm::SmallVector<Selector, 256> AllSelectors; 4785 for (auto &SelectorAndID : SelectorIDs) 4786 AllSelectors.push_back(SelectorAndID.first); 4787 for (auto &Selector : AllSelectors) 4788 SemaRef.updateOutOfDateSelector(Selector); 4789 4790 // Form the record of special types. 4791 RecordData SpecialTypes; 4792 AddTypeRef(Context.getRawCFConstantStringType(), SpecialTypes); 4793 AddTypeRef(Context.getFILEType(), SpecialTypes); 4794 AddTypeRef(Context.getjmp_bufType(), SpecialTypes); 4795 AddTypeRef(Context.getsigjmp_bufType(), SpecialTypes); 4796 AddTypeRef(Context.ObjCIdRedefinitionType, SpecialTypes); 4797 AddTypeRef(Context.ObjCClassRedefinitionType, SpecialTypes); 4798 AddTypeRef(Context.ObjCSelRedefinitionType, SpecialTypes); 4799 AddTypeRef(Context.getucontext_tType(), SpecialTypes); 4800 4801 if (Chain) { 4802 // Write the mapping information describing our module dependencies and how 4803 // each of those modules were mapped into our own offset/ID space, so that 4804 // the reader can build the appropriate mapping to its own offset/ID space. 4805 // The map consists solely of a blob with the following format: 4806 // *(module-kind:i8 4807 // module-name-len:i16 module-name:len*i8 4808 // source-location-offset:i32 4809 // identifier-id:i32 4810 // preprocessed-entity-id:i32 4811 // macro-definition-id:i32 4812 // submodule-id:i32 4813 // selector-id:i32 4814 // declaration-id:i32 4815 // c++-base-specifiers-id:i32 4816 // type-id:i32) 4817 // 4818 // module-kind is the ModuleKind enum value. If it is MK_PrebuiltModule, 4819 // MK_ExplicitModule or MK_ImplicitModule, then the module-name is the 4820 // module name. Otherwise, it is the module file name. 4821 auto Abbrev = std::make_shared<BitCodeAbbrev>(); 4822 Abbrev->Add(BitCodeAbbrevOp(MODULE_OFFSET_MAP)); 4823 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); 4824 unsigned ModuleOffsetMapAbbrev = Stream.EmitAbbrev(std::move(Abbrev)); 4825 SmallString<2048> Buffer; 4826 { 4827 llvm::raw_svector_ostream Out(Buffer); 4828 for (ModuleFile &M : Chain->ModuleMgr) { 4829 using namespace llvm::support; 4830 4831 endian::Writer LE(Out, little); 4832 LE.write<uint8_t>(static_cast<uint8_t>(M.Kind)); 4833 StringRef Name = M.isModule() ? M.ModuleName : M.FileName; 4834 LE.write<uint16_t>(Name.size()); 4835 Out.write(Name.data(), Name.size()); 4836 4837 // Note: if a base ID was uint max, it would not be possible to load 4838 // another module after it or have more than one entity inside it. 4839 uint32_t None = std::numeric_limits<uint32_t>::max(); 4840 4841 auto writeBaseIDOrNone = [&](auto BaseID, bool ShouldWrite) { 4842 assert(BaseID < std::numeric_limits<uint32_t>::max() && "base id too high"); 4843 if (ShouldWrite) 4844 LE.write<uint32_t>(BaseID); 4845 else 4846 LE.write<uint32_t>(None); 4847 }; 4848 4849 // These values should be unique within a chain, since they will be read 4850 // as keys into ContinuousRangeMaps. 4851 writeBaseIDOrNone(M.SLocEntryBaseOffset, M.LocalNumSLocEntries); 4852 writeBaseIDOrNone(M.BaseIdentifierID, M.LocalNumIdentifiers); 4853 writeBaseIDOrNone(M.BaseMacroID, M.LocalNumMacros); 4854 writeBaseIDOrNone(M.BasePreprocessedEntityID, 4855 M.NumPreprocessedEntities); 4856 writeBaseIDOrNone(M.BaseSubmoduleID, M.LocalNumSubmodules); 4857 writeBaseIDOrNone(M.BaseSelectorID, M.LocalNumSelectors); 4858 writeBaseIDOrNone(M.BaseDeclID, M.LocalNumDecls); 4859 writeBaseIDOrNone(M.BaseTypeIndex, M.LocalNumTypes); 4860 } 4861 } 4862 RecordData::value_type Record[] = {MODULE_OFFSET_MAP}; 4863 Stream.EmitRecordWithBlob(ModuleOffsetMapAbbrev, Record, 4864 Buffer.data(), Buffer.size()); 4865 } 4866 4867 // Build a record containing all of the DeclsToCheckForDeferredDiags. 4868 SmallVector<serialization::DeclID, 64> DeclsToCheckForDeferredDiags; 4869 for (auto *D : SemaRef.DeclsToCheckForDeferredDiags) 4870 DeclsToCheckForDeferredDiags.push_back(GetDeclRef(D)); 4871 4872 RecordData DeclUpdatesOffsetsRecord; 4873 4874 // Keep writing types, declarations, and declaration update records 4875 // until we've emitted all of them. 4876 Stream.EnterSubblock(DECLTYPES_BLOCK_ID, /*bits for abbreviations*/5); 4877 DeclTypesBlockStartOffset = Stream.GetCurrentBitNo(); 4878 WriteTypeAbbrevs(); 4879 WriteDeclAbbrevs(); 4880 do { 4881 WriteDeclUpdatesBlocks(DeclUpdatesOffsetsRecord); 4882 while (!DeclTypesToEmit.empty()) { 4883 DeclOrType DOT = DeclTypesToEmit.front(); 4884 DeclTypesToEmit.pop(); 4885 if (DOT.isType()) 4886 WriteType(DOT.getType()); 4887 else 4888 WriteDecl(Context, DOT.getDecl()); 4889 } 4890 } while (!DeclUpdates.empty()); 4891 Stream.ExitBlock(); 4892 4893 DoneWritingDeclsAndTypes = true; 4894 4895 // These things can only be done once we've written out decls and types. 4896 WriteTypeDeclOffsets(); 4897 if (!DeclUpdatesOffsetsRecord.empty()) 4898 Stream.EmitRecord(DECL_UPDATE_OFFSETS, DeclUpdatesOffsetsRecord); 4899 WriteFileDeclIDsMap(); 4900 WriteSourceManagerBlock(Context.getSourceManager(), PP); 4901 WriteComments(); 4902 WritePreprocessor(PP, isModule); 4903 WriteHeaderSearch(PP.getHeaderSearchInfo()); 4904 WriteSelectors(SemaRef); 4905 WriteReferencedSelectorsPool(SemaRef); 4906 WriteLateParsedTemplates(SemaRef); 4907 WriteIdentifierTable(PP, SemaRef.IdResolver, isModule); 4908 WriteFPPragmaOptions(SemaRef.CurFPFeatureOverrides()); 4909 WriteOpenCLExtensions(SemaRef); 4910 WriteCUDAPragmas(SemaRef); 4911 4912 // If we're emitting a module, write out the submodule information. 4913 if (WritingModule) 4914 WriteSubmodules(WritingModule); 4915 4916 Stream.EmitRecord(SPECIAL_TYPES, SpecialTypes); 4917 4918 // Write the record containing external, unnamed definitions. 4919 if (!EagerlyDeserializedDecls.empty()) 4920 Stream.EmitRecord(EAGERLY_DESERIALIZED_DECLS, EagerlyDeserializedDecls); 4921 4922 if (!ModularCodegenDecls.empty()) 4923 Stream.EmitRecord(MODULAR_CODEGEN_DECLS, ModularCodegenDecls); 4924 4925 // Write the record containing tentative definitions. 4926 if (!TentativeDefinitions.empty()) 4927 Stream.EmitRecord(TENTATIVE_DEFINITIONS, TentativeDefinitions); 4928 4929 // Write the record containing unused file scoped decls. 4930 if (!UnusedFileScopedDecls.empty()) 4931 Stream.EmitRecord(UNUSED_FILESCOPED_DECLS, UnusedFileScopedDecls); 4932 4933 // Write the record containing weak undeclared identifiers. 4934 if (!WeakUndeclaredIdentifiers.empty()) 4935 Stream.EmitRecord(WEAK_UNDECLARED_IDENTIFIERS, 4936 WeakUndeclaredIdentifiers); 4937 4938 // Write the record containing ext_vector type names. 4939 if (!ExtVectorDecls.empty()) 4940 Stream.EmitRecord(EXT_VECTOR_DECLS, ExtVectorDecls); 4941 4942 // Write the record containing VTable uses information. 4943 if (!VTableUses.empty()) 4944 Stream.EmitRecord(VTABLE_USES, VTableUses); 4945 4946 // Write the record containing potentially unused local typedefs. 4947 if (!UnusedLocalTypedefNameCandidates.empty()) 4948 Stream.EmitRecord(UNUSED_LOCAL_TYPEDEF_NAME_CANDIDATES, 4949 UnusedLocalTypedefNameCandidates); 4950 4951 // Write the record containing pending implicit instantiations. 4952 if (!PendingInstantiations.empty()) 4953 Stream.EmitRecord(PENDING_IMPLICIT_INSTANTIATIONS, PendingInstantiations); 4954 4955 // Write the record containing declaration references of Sema. 4956 if (!SemaDeclRefs.empty()) 4957 Stream.EmitRecord(SEMA_DECL_REFS, SemaDeclRefs); 4958 4959 // Write the record containing decls to be checked for deferred diags. 4960 if (!DeclsToCheckForDeferredDiags.empty()) 4961 Stream.EmitRecord(DECLS_TO_CHECK_FOR_DEFERRED_DIAGS, 4962 DeclsToCheckForDeferredDiags); 4963 4964 // Write the record containing CUDA-specific declaration references. 4965 if (!CUDASpecialDeclRefs.empty()) 4966 Stream.EmitRecord(CUDA_SPECIAL_DECL_REFS, CUDASpecialDeclRefs); 4967 4968 // Write the delegating constructors. 4969 if (!DelegatingCtorDecls.empty()) 4970 Stream.EmitRecord(DELEGATING_CTORS, DelegatingCtorDecls); 4971 4972 // Write the known namespaces. 4973 if (!KnownNamespaces.empty()) 4974 Stream.EmitRecord(KNOWN_NAMESPACES, KnownNamespaces); 4975 4976 // Write the undefined internal functions and variables, and inline functions. 4977 if (!UndefinedButUsed.empty()) 4978 Stream.EmitRecord(UNDEFINED_BUT_USED, UndefinedButUsed); 4979 4980 if (!DeleteExprsToAnalyze.empty()) 4981 Stream.EmitRecord(DELETE_EXPRS_TO_ANALYZE, DeleteExprsToAnalyze); 4982 4983 // Write the visible updates to DeclContexts. 4984 for (auto *DC : UpdatedDeclContexts) 4985 WriteDeclContextVisibleUpdate(DC); 4986 4987 if (!WritingModule) { 4988 // Write the submodules that were imported, if any. 4989 struct ModuleInfo { 4990 uint64_t ID; 4991 Module *M; 4992 ModuleInfo(uint64_t ID, Module *M) : ID(ID), M(M) {} 4993 }; 4994 llvm::SmallVector<ModuleInfo, 64> Imports; 4995 for (const auto *I : Context.local_imports()) { 4996 assert(SubmoduleIDs.find(I->getImportedModule()) != SubmoduleIDs.end()); 4997 Imports.push_back(ModuleInfo(SubmoduleIDs[I->getImportedModule()], 4998 I->getImportedModule())); 4999 } 5000 5001 if (!Imports.empty()) { 5002 auto Cmp = [](const ModuleInfo &A, const ModuleInfo &B) { 5003 return A.ID < B.ID; 5004 }; 5005 auto Eq = [](const ModuleInfo &A, const ModuleInfo &B) { 5006 return A.ID == B.ID; 5007 }; 5008 5009 // Sort and deduplicate module IDs. 5010 llvm::sort(Imports, Cmp); 5011 Imports.erase(std::unique(Imports.begin(), Imports.end(), Eq), 5012 Imports.end()); 5013 5014 RecordData ImportedModules; 5015 for (const auto &Import : Imports) { 5016 ImportedModules.push_back(Import.ID); 5017 // FIXME: If the module has macros imported then later has declarations 5018 // imported, this location won't be the right one as a location for the 5019 // declaration imports. 5020 AddSourceLocation(PP.getModuleImportLoc(Import.M), ImportedModules); 5021 } 5022 5023 Stream.EmitRecord(IMPORTED_MODULES, ImportedModules); 5024 } 5025 } 5026 5027 WriteObjCCategories(); 5028 if(!WritingModule) { 5029 WriteOptimizePragmaOptions(SemaRef); 5030 WriteMSStructPragmaOptions(SemaRef); 5031 WriteMSPointersToMembersPragmaOptions(SemaRef); 5032 } 5033 WritePackPragmaOptions(SemaRef); 5034 WriteFloatControlPragmaOptions(SemaRef); 5035 5036 // Some simple statistics 5037 RecordData::value_type Record[] = { 5038 NumStatements, NumMacros, NumLexicalDeclContexts, NumVisibleDeclContexts}; 5039 Stream.EmitRecord(STATISTICS, Record); 5040 Stream.ExitBlock(); 5041 Stream.FlushToWord(); 5042 ASTBlockRange.second = Stream.GetCurrentBitNo(); 5043 5044 // Write the module file extension blocks. 5045 for (const auto &ExtWriter : ModuleFileExtensionWriters) 5046 WriteModuleFileExtension(SemaRef, *ExtWriter); 5047 5048 return writeUnhashedControlBlock(PP, Context); 5049 } 5050 5051 void ASTWriter::WriteDeclUpdatesBlocks(RecordDataImpl &OffsetsRecord) { 5052 if (DeclUpdates.empty()) 5053 return; 5054 5055 DeclUpdateMap LocalUpdates; 5056 LocalUpdates.swap(DeclUpdates); 5057 5058 for (auto &DeclUpdate : LocalUpdates) { 5059 const Decl *D = DeclUpdate.first; 5060 5061 bool HasUpdatedBody = false; 5062 RecordData RecordData; 5063 ASTRecordWriter Record(*this, RecordData); 5064 for (auto &Update : DeclUpdate.second) { 5065 DeclUpdateKind Kind = (DeclUpdateKind)Update.getKind(); 5066 5067 // An updated body is emitted last, so that the reader doesn't need 5068 // to skip over the lazy body to reach statements for other records. 5069 if (Kind == UPD_CXX_ADDED_FUNCTION_DEFINITION) 5070 HasUpdatedBody = true; 5071 else 5072 Record.push_back(Kind); 5073 5074 switch (Kind) { 5075 case UPD_CXX_ADDED_IMPLICIT_MEMBER: 5076 case UPD_CXX_ADDED_TEMPLATE_SPECIALIZATION: 5077 case UPD_CXX_ADDED_ANONYMOUS_NAMESPACE: 5078 assert(Update.getDecl() && "no decl to add?"); 5079 Record.push_back(GetDeclRef(Update.getDecl())); 5080 break; 5081 5082 case UPD_CXX_ADDED_FUNCTION_DEFINITION: 5083 break; 5084 5085 case UPD_CXX_POINT_OF_INSTANTIATION: 5086 // FIXME: Do we need to also save the template specialization kind here? 5087 Record.AddSourceLocation(Update.getLoc()); 5088 break; 5089 5090 case UPD_CXX_ADDED_VAR_DEFINITION: { 5091 const VarDecl *VD = cast<VarDecl>(D); 5092 Record.push_back(VD->isInline()); 5093 Record.push_back(VD->isInlineSpecified()); 5094 Record.AddVarDeclInit(VD); 5095 break; 5096 } 5097 5098 case UPD_CXX_INSTANTIATED_DEFAULT_ARGUMENT: 5099 Record.AddStmt(const_cast<Expr *>( 5100 cast<ParmVarDecl>(Update.getDecl())->getDefaultArg())); 5101 break; 5102 5103 case UPD_CXX_INSTANTIATED_DEFAULT_MEMBER_INITIALIZER: 5104 Record.AddStmt( 5105 cast<FieldDecl>(Update.getDecl())->getInClassInitializer()); 5106 break; 5107 5108 case UPD_CXX_INSTANTIATED_CLASS_DEFINITION: { 5109 auto *RD = cast<CXXRecordDecl>(D); 5110 UpdatedDeclContexts.insert(RD->getPrimaryContext()); 5111 Record.push_back(RD->isParamDestroyedInCallee()); 5112 Record.push_back(RD->getArgPassingRestrictions()); 5113 Record.AddCXXDefinitionData(RD); 5114 Record.AddOffset(WriteDeclContextLexicalBlock( 5115 *Context, const_cast<CXXRecordDecl *>(RD))); 5116 5117 // This state is sometimes updated by template instantiation, when we 5118 // switch from the specialization referring to the template declaration 5119 // to it referring to the template definition. 5120 if (auto *MSInfo = RD->getMemberSpecializationInfo()) { 5121 Record.push_back(MSInfo->getTemplateSpecializationKind()); 5122 Record.AddSourceLocation(MSInfo->getPointOfInstantiation()); 5123 } else { 5124 auto *Spec = cast<ClassTemplateSpecializationDecl>(RD); 5125 Record.push_back(Spec->getTemplateSpecializationKind()); 5126 Record.AddSourceLocation(Spec->getPointOfInstantiation()); 5127 5128 // The instantiation might have been resolved to a partial 5129 // specialization. If so, record which one. 5130 auto From = Spec->getInstantiatedFrom(); 5131 if (auto PartialSpec = 5132 From.dyn_cast<ClassTemplatePartialSpecializationDecl*>()) { 5133 Record.push_back(true); 5134 Record.AddDeclRef(PartialSpec); 5135 Record.AddTemplateArgumentList( 5136 &Spec->getTemplateInstantiationArgs()); 5137 } else { 5138 Record.push_back(false); 5139 } 5140 } 5141 Record.push_back(RD->getTagKind()); 5142 Record.AddSourceLocation(RD->getLocation()); 5143 Record.AddSourceLocation(RD->getBeginLoc()); 5144 Record.AddSourceRange(RD->getBraceRange()); 5145 5146 // Instantiation may change attributes; write them all out afresh. 5147 Record.push_back(D->hasAttrs()); 5148 if (D->hasAttrs()) 5149 Record.AddAttributes(D->getAttrs()); 5150 5151 // FIXME: Ensure we don't get here for explicit instantiations. 5152 break; 5153 } 5154 5155 case UPD_CXX_RESOLVED_DTOR_DELETE: 5156 Record.AddDeclRef(Update.getDecl()); 5157 Record.AddStmt(cast<CXXDestructorDecl>(D)->getOperatorDeleteThisArg()); 5158 break; 5159 5160 case UPD_CXX_RESOLVED_EXCEPTION_SPEC: { 5161 auto prototype = 5162 cast<FunctionDecl>(D)->getType()->castAs<FunctionProtoType>(); 5163 Record.writeExceptionSpecInfo(prototype->getExceptionSpecInfo()); 5164 break; 5165 } 5166 5167 case UPD_CXX_DEDUCED_RETURN_TYPE: 5168 Record.push_back(GetOrCreateTypeID(Update.getType())); 5169 break; 5170 5171 case UPD_DECL_MARKED_USED: 5172 break; 5173 5174 case UPD_MANGLING_NUMBER: 5175 case UPD_STATIC_LOCAL_NUMBER: 5176 Record.push_back(Update.getNumber()); 5177 break; 5178 5179 case UPD_DECL_MARKED_OPENMP_THREADPRIVATE: 5180 Record.AddSourceRange( 5181 D->getAttr<OMPThreadPrivateDeclAttr>()->getRange()); 5182 break; 5183 5184 case UPD_DECL_MARKED_OPENMP_ALLOCATE: { 5185 auto *A = D->getAttr<OMPAllocateDeclAttr>(); 5186 Record.push_back(A->getAllocatorType()); 5187 Record.AddStmt(A->getAllocator()); 5188 Record.AddStmt(A->getAlignment()); 5189 Record.AddSourceRange(A->getRange()); 5190 break; 5191 } 5192 5193 case UPD_DECL_MARKED_OPENMP_DECLARETARGET: 5194 Record.push_back(D->getAttr<OMPDeclareTargetDeclAttr>()->getMapType()); 5195 Record.AddSourceRange( 5196 D->getAttr<OMPDeclareTargetDeclAttr>()->getRange()); 5197 break; 5198 5199 case UPD_DECL_EXPORTED: 5200 Record.push_back(getSubmoduleID(Update.getModule())); 5201 break; 5202 5203 case UPD_ADDED_ATTR_TO_RECORD: 5204 Record.AddAttributes(llvm::makeArrayRef(Update.getAttr())); 5205 break; 5206 } 5207 } 5208 5209 if (HasUpdatedBody) { 5210 const auto *Def = cast<FunctionDecl>(D); 5211 Record.push_back(UPD_CXX_ADDED_FUNCTION_DEFINITION); 5212 Record.push_back(Def->isInlined()); 5213 Record.AddSourceLocation(Def->getInnerLocStart()); 5214 Record.AddFunctionDefinition(Def); 5215 } 5216 5217 OffsetsRecord.push_back(GetDeclRef(D)); 5218 OffsetsRecord.push_back(Record.Emit(DECL_UPDATES)); 5219 } 5220 } 5221 5222 void ASTWriter::AddAlignPackInfo(const Sema::AlignPackInfo &Info, 5223 RecordDataImpl &Record) { 5224 uint32_t Raw = Sema::AlignPackInfo::getRawEncoding(Info); 5225 Record.push_back(Raw); 5226 } 5227 5228 void ASTWriter::AddSourceLocation(SourceLocation Loc, RecordDataImpl &Record, 5229 SourceLocationSequence *Seq) { 5230 Record.push_back(SourceLocationEncoding::encode(Loc, Seq)); 5231 } 5232 5233 void ASTWriter::AddSourceRange(SourceRange Range, RecordDataImpl &Record, 5234 SourceLocationSequence *Seq) { 5235 AddSourceLocation(Range.getBegin(), Record, Seq); 5236 AddSourceLocation(Range.getEnd(), Record, Seq); 5237 } 5238 5239 void ASTRecordWriter::AddAPFloat(const llvm::APFloat &Value) { 5240 AddAPInt(Value.bitcastToAPInt()); 5241 } 5242 5243 void ASTWriter::AddIdentifierRef(const IdentifierInfo *II, RecordDataImpl &Record) { 5244 Record.push_back(getIdentifierRef(II)); 5245 } 5246 5247 IdentID ASTWriter::getIdentifierRef(const IdentifierInfo *II) { 5248 if (!II) 5249 return 0; 5250 5251 IdentID &ID = IdentifierIDs[II]; 5252 if (ID == 0) 5253 ID = NextIdentID++; 5254 return ID; 5255 } 5256 5257 MacroID ASTWriter::getMacroRef(MacroInfo *MI, const IdentifierInfo *Name) { 5258 // Don't emit builtin macros like __LINE__ to the AST file unless they 5259 // have been redefined by the header (in which case they are not 5260 // isBuiltinMacro). 5261 if (!MI || MI->isBuiltinMacro()) 5262 return 0; 5263 5264 MacroID &ID = MacroIDs[MI]; 5265 if (ID == 0) { 5266 ID = NextMacroID++; 5267 MacroInfoToEmitData Info = { Name, MI, ID }; 5268 MacroInfosToEmit.push_back(Info); 5269 } 5270 return ID; 5271 } 5272 5273 MacroID ASTWriter::getMacroID(MacroInfo *MI) { 5274 if (!MI || MI->isBuiltinMacro()) 5275 return 0; 5276 5277 assert(MacroIDs.find(MI) != MacroIDs.end() && "Macro not emitted!"); 5278 return MacroIDs[MI]; 5279 } 5280 5281 uint32_t ASTWriter::getMacroDirectivesOffset(const IdentifierInfo *Name) { 5282 return IdentMacroDirectivesOffsetMap.lookup(Name); 5283 } 5284 5285 void ASTRecordWriter::AddSelectorRef(const Selector SelRef) { 5286 Record->push_back(Writer->getSelectorRef(SelRef)); 5287 } 5288 5289 SelectorID ASTWriter::getSelectorRef(Selector Sel) { 5290 if (Sel.getAsOpaquePtr() == nullptr) { 5291 return 0; 5292 } 5293 5294 SelectorID SID = SelectorIDs[Sel]; 5295 if (SID == 0 && Chain) { 5296 // This might trigger a ReadSelector callback, which will set the ID for 5297 // this selector. 5298 Chain->LoadSelector(Sel); 5299 SID = SelectorIDs[Sel]; 5300 } 5301 if (SID == 0) { 5302 SID = NextSelectorID++; 5303 SelectorIDs[Sel] = SID; 5304 } 5305 return SID; 5306 } 5307 5308 void ASTRecordWriter::AddCXXTemporary(const CXXTemporary *Temp) { 5309 AddDeclRef(Temp->getDestructor()); 5310 } 5311 5312 void ASTRecordWriter::AddTemplateArgumentLocInfo( 5313 TemplateArgument::ArgKind Kind, const TemplateArgumentLocInfo &Arg) { 5314 switch (Kind) { 5315 case TemplateArgument::Expression: 5316 AddStmt(Arg.getAsExpr()); 5317 break; 5318 case TemplateArgument::Type: 5319 AddTypeSourceInfo(Arg.getAsTypeSourceInfo()); 5320 break; 5321 case TemplateArgument::Template: 5322 AddNestedNameSpecifierLoc(Arg.getTemplateQualifierLoc()); 5323 AddSourceLocation(Arg.getTemplateNameLoc()); 5324 break; 5325 case TemplateArgument::TemplateExpansion: 5326 AddNestedNameSpecifierLoc(Arg.getTemplateQualifierLoc()); 5327 AddSourceLocation(Arg.getTemplateNameLoc()); 5328 AddSourceLocation(Arg.getTemplateEllipsisLoc()); 5329 break; 5330 case TemplateArgument::Null: 5331 case TemplateArgument::Integral: 5332 case TemplateArgument::Declaration: 5333 case TemplateArgument::NullPtr: 5334 case TemplateArgument::Pack: 5335 // FIXME: Is this right? 5336 break; 5337 } 5338 } 5339 5340 void ASTRecordWriter::AddTemplateArgumentLoc(const TemplateArgumentLoc &Arg) { 5341 AddTemplateArgument(Arg.getArgument()); 5342 5343 if (Arg.getArgument().getKind() == TemplateArgument::Expression) { 5344 bool InfoHasSameExpr 5345 = Arg.getArgument().getAsExpr() == Arg.getLocInfo().getAsExpr(); 5346 Record->push_back(InfoHasSameExpr); 5347 if (InfoHasSameExpr) 5348 return; // Avoid storing the same expr twice. 5349 } 5350 AddTemplateArgumentLocInfo(Arg.getArgument().getKind(), Arg.getLocInfo()); 5351 } 5352 5353 void ASTRecordWriter::AddTypeSourceInfo(TypeSourceInfo *TInfo) { 5354 if (!TInfo) { 5355 AddTypeRef(QualType()); 5356 return; 5357 } 5358 5359 AddTypeRef(TInfo->getType()); 5360 AddTypeLoc(TInfo->getTypeLoc()); 5361 } 5362 5363 void ASTRecordWriter::AddTypeLoc(TypeLoc TL, LocSeq *OuterSeq) { 5364 LocSeq::State Seq(OuterSeq); 5365 TypeLocWriter TLW(*this, Seq); 5366 for (; !TL.isNull(); TL = TL.getNextTypeLoc()) 5367 TLW.Visit(TL); 5368 } 5369 5370 void ASTWriter::AddTypeRef(QualType T, RecordDataImpl &Record) { 5371 Record.push_back(GetOrCreateTypeID(T)); 5372 } 5373 5374 TypeID ASTWriter::GetOrCreateTypeID(QualType T) { 5375 assert(Context); 5376 return MakeTypeID(*Context, T, [&](QualType T) -> TypeIdx { 5377 if (T.isNull()) 5378 return TypeIdx(); 5379 assert(!T.getLocalFastQualifiers()); 5380 5381 TypeIdx &Idx = TypeIdxs[T]; 5382 if (Idx.getIndex() == 0) { 5383 if (DoneWritingDeclsAndTypes) { 5384 assert(0 && "New type seen after serializing all the types to emit!"); 5385 return TypeIdx(); 5386 } 5387 5388 // We haven't seen this type before. Assign it a new ID and put it 5389 // into the queue of types to emit. 5390 Idx = TypeIdx(NextTypeID++); 5391 DeclTypesToEmit.push(T); 5392 } 5393 return Idx; 5394 }); 5395 } 5396 5397 TypeID ASTWriter::getTypeID(QualType T) const { 5398 assert(Context); 5399 return MakeTypeID(*Context, T, [&](QualType T) -> TypeIdx { 5400 if (T.isNull()) 5401 return TypeIdx(); 5402 assert(!T.getLocalFastQualifiers()); 5403 5404 TypeIdxMap::const_iterator I = TypeIdxs.find(T); 5405 assert(I != TypeIdxs.end() && "Type not emitted!"); 5406 return I->second; 5407 }); 5408 } 5409 5410 void ASTWriter::AddDeclRef(const Decl *D, RecordDataImpl &Record) { 5411 Record.push_back(GetDeclRef(D)); 5412 } 5413 5414 DeclID ASTWriter::GetDeclRef(const Decl *D) { 5415 assert(WritingAST && "Cannot request a declaration ID before AST writing"); 5416 5417 if (!D) { 5418 return 0; 5419 } 5420 5421 // If D comes from an AST file, its declaration ID is already known and 5422 // fixed. 5423 if (D->isFromASTFile()) 5424 return D->getGlobalID(); 5425 5426 assert(!(reinterpret_cast<uintptr_t>(D) & 0x01) && "Invalid decl pointer"); 5427 DeclID &ID = DeclIDs[D]; 5428 if (ID == 0) { 5429 if (DoneWritingDeclsAndTypes) { 5430 assert(0 && "New decl seen after serializing all the decls to emit!"); 5431 return 0; 5432 } 5433 5434 // We haven't seen this declaration before. Give it a new ID and 5435 // enqueue it in the list of declarations to emit. 5436 ID = NextDeclID++; 5437 DeclTypesToEmit.push(const_cast<Decl *>(D)); 5438 } 5439 5440 return ID; 5441 } 5442 5443 DeclID ASTWriter::getDeclID(const Decl *D) { 5444 if (!D) 5445 return 0; 5446 5447 // If D comes from an AST file, its declaration ID is already known and 5448 // fixed. 5449 if (D->isFromASTFile()) 5450 return D->getGlobalID(); 5451 5452 assert(DeclIDs.find(D) != DeclIDs.end() && "Declaration not emitted!"); 5453 return DeclIDs[D]; 5454 } 5455 5456 void ASTWriter::associateDeclWithFile(const Decl *D, DeclID ID) { 5457 assert(ID); 5458 assert(D); 5459 5460 SourceLocation Loc = D->getLocation(); 5461 if (Loc.isInvalid()) 5462 return; 5463 5464 // We only keep track of the file-level declarations of each file. 5465 if (!D->getLexicalDeclContext()->isFileContext()) 5466 return; 5467 // FIXME: ParmVarDecls that are part of a function type of a parameter of 5468 // a function/objc method, should not have TU as lexical context. 5469 // TemplateTemplateParmDecls that are part of an alias template, should not 5470 // have TU as lexical context. 5471 if (isa<ParmVarDecl>(D) || isa<TemplateTemplateParmDecl>(D)) 5472 return; 5473 5474 SourceManager &SM = Context->getSourceManager(); 5475 SourceLocation FileLoc = SM.getFileLoc(Loc); 5476 assert(SM.isLocalSourceLocation(FileLoc)); 5477 FileID FID; 5478 unsigned Offset; 5479 std::tie(FID, Offset) = SM.getDecomposedLoc(FileLoc); 5480 if (FID.isInvalid()) 5481 return; 5482 assert(SM.getSLocEntry(FID).isFile()); 5483 5484 std::unique_ptr<DeclIDInFileInfo> &Info = FileDeclIDs[FID]; 5485 if (!Info) 5486 Info = std::make_unique<DeclIDInFileInfo>(); 5487 5488 std::pair<unsigned, serialization::DeclID> LocDecl(Offset, ID); 5489 LocDeclIDsTy &Decls = Info->DeclIDs; 5490 Decls.push_back(LocDecl); 5491 } 5492 5493 unsigned ASTWriter::getAnonymousDeclarationNumber(const NamedDecl *D) { 5494 assert(needsAnonymousDeclarationNumber(D) && 5495 "expected an anonymous declaration"); 5496 5497 // Number the anonymous declarations within this context, if we've not 5498 // already done so. 5499 auto It = AnonymousDeclarationNumbers.find(D); 5500 if (It == AnonymousDeclarationNumbers.end()) { 5501 auto *DC = D->getLexicalDeclContext(); 5502 numberAnonymousDeclsWithin(DC, [&](const NamedDecl *ND, unsigned Number) { 5503 AnonymousDeclarationNumbers[ND] = Number; 5504 }); 5505 5506 It = AnonymousDeclarationNumbers.find(D); 5507 assert(It != AnonymousDeclarationNumbers.end() && 5508 "declaration not found within its lexical context"); 5509 } 5510 5511 return It->second; 5512 } 5513 5514 void ASTRecordWriter::AddDeclarationNameLoc(const DeclarationNameLoc &DNLoc, 5515 DeclarationName Name) { 5516 switch (Name.getNameKind()) { 5517 case DeclarationName::CXXConstructorName: 5518 case DeclarationName::CXXDestructorName: 5519 case DeclarationName::CXXConversionFunctionName: 5520 AddTypeSourceInfo(DNLoc.getNamedTypeInfo()); 5521 break; 5522 5523 case DeclarationName::CXXOperatorName: 5524 AddSourceRange(DNLoc.getCXXOperatorNameRange()); 5525 break; 5526 5527 case DeclarationName::CXXLiteralOperatorName: 5528 AddSourceLocation(DNLoc.getCXXLiteralOperatorNameLoc()); 5529 break; 5530 5531 case DeclarationName::Identifier: 5532 case DeclarationName::ObjCZeroArgSelector: 5533 case DeclarationName::ObjCOneArgSelector: 5534 case DeclarationName::ObjCMultiArgSelector: 5535 case DeclarationName::CXXUsingDirective: 5536 case DeclarationName::CXXDeductionGuideName: 5537 break; 5538 } 5539 } 5540 5541 void ASTRecordWriter::AddDeclarationNameInfo( 5542 const DeclarationNameInfo &NameInfo) { 5543 AddDeclarationName(NameInfo.getName()); 5544 AddSourceLocation(NameInfo.getLoc()); 5545 AddDeclarationNameLoc(NameInfo.getInfo(), NameInfo.getName()); 5546 } 5547 5548 void ASTRecordWriter::AddQualifierInfo(const QualifierInfo &Info) { 5549 AddNestedNameSpecifierLoc(Info.QualifierLoc); 5550 Record->push_back(Info.NumTemplParamLists); 5551 for (unsigned i = 0, e = Info.NumTemplParamLists; i != e; ++i) 5552 AddTemplateParameterList(Info.TemplParamLists[i]); 5553 } 5554 5555 void ASTRecordWriter::AddNestedNameSpecifierLoc(NestedNameSpecifierLoc NNS) { 5556 // Nested name specifiers usually aren't too long. I think that 8 would 5557 // typically accommodate the vast majority. 5558 SmallVector<NestedNameSpecifierLoc , 8> NestedNames; 5559 5560 // Push each of the nested-name-specifiers's onto a stack for 5561 // serialization in reverse order. 5562 while (NNS) { 5563 NestedNames.push_back(NNS); 5564 NNS = NNS.getPrefix(); 5565 } 5566 5567 Record->push_back(NestedNames.size()); 5568 while(!NestedNames.empty()) { 5569 NNS = NestedNames.pop_back_val(); 5570 NestedNameSpecifier::SpecifierKind Kind 5571 = NNS.getNestedNameSpecifier()->getKind(); 5572 Record->push_back(Kind); 5573 switch (Kind) { 5574 case NestedNameSpecifier::Identifier: 5575 AddIdentifierRef(NNS.getNestedNameSpecifier()->getAsIdentifier()); 5576 AddSourceRange(NNS.getLocalSourceRange()); 5577 break; 5578 5579 case NestedNameSpecifier::Namespace: 5580 AddDeclRef(NNS.getNestedNameSpecifier()->getAsNamespace()); 5581 AddSourceRange(NNS.getLocalSourceRange()); 5582 break; 5583 5584 case NestedNameSpecifier::NamespaceAlias: 5585 AddDeclRef(NNS.getNestedNameSpecifier()->getAsNamespaceAlias()); 5586 AddSourceRange(NNS.getLocalSourceRange()); 5587 break; 5588 5589 case NestedNameSpecifier::TypeSpec: 5590 case NestedNameSpecifier::TypeSpecWithTemplate: 5591 Record->push_back(Kind == NestedNameSpecifier::TypeSpecWithTemplate); 5592 AddTypeRef(NNS.getTypeLoc().getType()); 5593 AddTypeLoc(NNS.getTypeLoc()); 5594 AddSourceLocation(NNS.getLocalSourceRange().getEnd()); 5595 break; 5596 5597 case NestedNameSpecifier::Global: 5598 AddSourceLocation(NNS.getLocalSourceRange().getEnd()); 5599 break; 5600 5601 case NestedNameSpecifier::Super: 5602 AddDeclRef(NNS.getNestedNameSpecifier()->getAsRecordDecl()); 5603 AddSourceRange(NNS.getLocalSourceRange()); 5604 break; 5605 } 5606 } 5607 } 5608 5609 void ASTRecordWriter::AddTemplateParameterList( 5610 const TemplateParameterList *TemplateParams) { 5611 assert(TemplateParams && "No TemplateParams!"); 5612 AddSourceLocation(TemplateParams->getTemplateLoc()); 5613 AddSourceLocation(TemplateParams->getLAngleLoc()); 5614 AddSourceLocation(TemplateParams->getRAngleLoc()); 5615 5616 Record->push_back(TemplateParams->size()); 5617 for (const auto &P : *TemplateParams) 5618 AddDeclRef(P); 5619 if (const Expr *RequiresClause = TemplateParams->getRequiresClause()) { 5620 Record->push_back(true); 5621 AddStmt(const_cast<Expr*>(RequiresClause)); 5622 } else { 5623 Record->push_back(false); 5624 } 5625 } 5626 5627 /// Emit a template argument list. 5628 void ASTRecordWriter::AddTemplateArgumentList( 5629 const TemplateArgumentList *TemplateArgs) { 5630 assert(TemplateArgs && "No TemplateArgs!"); 5631 Record->push_back(TemplateArgs->size()); 5632 for (int i = 0, e = TemplateArgs->size(); i != e; ++i) 5633 AddTemplateArgument(TemplateArgs->get(i)); 5634 } 5635 5636 void ASTRecordWriter::AddASTTemplateArgumentListInfo( 5637 const ASTTemplateArgumentListInfo *ASTTemplArgList) { 5638 assert(ASTTemplArgList && "No ASTTemplArgList!"); 5639 AddSourceLocation(ASTTemplArgList->LAngleLoc); 5640 AddSourceLocation(ASTTemplArgList->RAngleLoc); 5641 Record->push_back(ASTTemplArgList->NumTemplateArgs); 5642 const TemplateArgumentLoc *TemplArgs = ASTTemplArgList->getTemplateArgs(); 5643 for (int i = 0, e = ASTTemplArgList->NumTemplateArgs; i != e; ++i) 5644 AddTemplateArgumentLoc(TemplArgs[i]); 5645 } 5646 5647 void ASTRecordWriter::AddUnresolvedSet(const ASTUnresolvedSet &Set) { 5648 Record->push_back(Set.size()); 5649 for (ASTUnresolvedSet::const_iterator 5650 I = Set.begin(), E = Set.end(); I != E; ++I) { 5651 AddDeclRef(I.getDecl()); 5652 Record->push_back(I.getAccess()); 5653 } 5654 } 5655 5656 // FIXME: Move this out of the main ASTRecordWriter interface. 5657 void ASTRecordWriter::AddCXXBaseSpecifier(const CXXBaseSpecifier &Base) { 5658 Record->push_back(Base.isVirtual()); 5659 Record->push_back(Base.isBaseOfClass()); 5660 Record->push_back(Base.getAccessSpecifierAsWritten()); 5661 Record->push_back(Base.getInheritConstructors()); 5662 AddTypeSourceInfo(Base.getTypeSourceInfo()); 5663 AddSourceRange(Base.getSourceRange()); 5664 AddSourceLocation(Base.isPackExpansion()? Base.getEllipsisLoc() 5665 : SourceLocation()); 5666 } 5667 5668 static uint64_t EmitCXXBaseSpecifiers(ASTWriter &W, 5669 ArrayRef<CXXBaseSpecifier> Bases) { 5670 ASTWriter::RecordData Record; 5671 ASTRecordWriter Writer(W, Record); 5672 Writer.push_back(Bases.size()); 5673 5674 for (auto &Base : Bases) 5675 Writer.AddCXXBaseSpecifier(Base); 5676 5677 return Writer.Emit(serialization::DECL_CXX_BASE_SPECIFIERS); 5678 } 5679 5680 // FIXME: Move this out of the main ASTRecordWriter interface. 5681 void ASTRecordWriter::AddCXXBaseSpecifiers(ArrayRef<CXXBaseSpecifier> Bases) { 5682 AddOffset(EmitCXXBaseSpecifiers(*Writer, Bases)); 5683 } 5684 5685 static uint64_t 5686 EmitCXXCtorInitializers(ASTWriter &W, 5687 ArrayRef<CXXCtorInitializer *> CtorInits) { 5688 ASTWriter::RecordData Record; 5689 ASTRecordWriter Writer(W, Record); 5690 Writer.push_back(CtorInits.size()); 5691 5692 for (auto *Init : CtorInits) { 5693 if (Init->isBaseInitializer()) { 5694 Writer.push_back(CTOR_INITIALIZER_BASE); 5695 Writer.AddTypeSourceInfo(Init->getTypeSourceInfo()); 5696 Writer.push_back(Init->isBaseVirtual()); 5697 } else if (Init->isDelegatingInitializer()) { 5698 Writer.push_back(CTOR_INITIALIZER_DELEGATING); 5699 Writer.AddTypeSourceInfo(Init->getTypeSourceInfo()); 5700 } else if (Init->isMemberInitializer()){ 5701 Writer.push_back(CTOR_INITIALIZER_MEMBER); 5702 Writer.AddDeclRef(Init->getMember()); 5703 } else { 5704 Writer.push_back(CTOR_INITIALIZER_INDIRECT_MEMBER); 5705 Writer.AddDeclRef(Init->getIndirectMember()); 5706 } 5707 5708 Writer.AddSourceLocation(Init->getMemberLocation()); 5709 Writer.AddStmt(Init->getInit()); 5710 Writer.AddSourceLocation(Init->getLParenLoc()); 5711 Writer.AddSourceLocation(Init->getRParenLoc()); 5712 Writer.push_back(Init->isWritten()); 5713 if (Init->isWritten()) 5714 Writer.push_back(Init->getSourceOrder()); 5715 } 5716 5717 return Writer.Emit(serialization::DECL_CXX_CTOR_INITIALIZERS); 5718 } 5719 5720 // FIXME: Move this out of the main ASTRecordWriter interface. 5721 void ASTRecordWriter::AddCXXCtorInitializers( 5722 ArrayRef<CXXCtorInitializer *> CtorInits) { 5723 AddOffset(EmitCXXCtorInitializers(*Writer, CtorInits)); 5724 } 5725 5726 void ASTRecordWriter::AddCXXDefinitionData(const CXXRecordDecl *D) { 5727 auto &Data = D->data(); 5728 Record->push_back(Data.IsLambda); 5729 5730 #define FIELD(Name, Width, Merge) \ 5731 Record->push_back(Data.Name); 5732 #include "clang/AST/CXXRecordDeclDefinitionBits.def" 5733 5734 // getODRHash will compute the ODRHash if it has not been previously computed. 5735 Record->push_back(D->getODRHash()); 5736 bool ModulesDebugInfo = 5737 Writer->Context->getLangOpts().ModulesDebugInfo && !D->isDependentType(); 5738 Record->push_back(ModulesDebugInfo); 5739 if (ModulesDebugInfo) 5740 Writer->ModularCodegenDecls.push_back(Writer->GetDeclRef(D)); 5741 5742 // IsLambda bit is already saved. 5743 5744 Record->push_back(Data.NumBases); 5745 if (Data.NumBases > 0) 5746 AddCXXBaseSpecifiers(Data.bases()); 5747 5748 // FIXME: Make VBases lazily computed when needed to avoid storing them. 5749 Record->push_back(Data.NumVBases); 5750 if (Data.NumVBases > 0) 5751 AddCXXBaseSpecifiers(Data.vbases()); 5752 5753 AddUnresolvedSet(Data.Conversions.get(*Writer->Context)); 5754 Record->push_back(Data.ComputedVisibleConversions); 5755 if (Data.ComputedVisibleConversions) 5756 AddUnresolvedSet(Data.VisibleConversions.get(*Writer->Context)); 5757 // Data.Definition is the owning decl, no need to write it. 5758 AddDeclRef(D->getFirstFriend()); 5759 5760 // Add lambda-specific data. 5761 if (Data.IsLambda) { 5762 auto &Lambda = D->getLambdaData(); 5763 Record->push_back(Lambda.DependencyKind); 5764 Record->push_back(Lambda.IsGenericLambda); 5765 Record->push_back(Lambda.CaptureDefault); 5766 Record->push_back(Lambda.NumCaptures); 5767 Record->push_back(Lambda.NumExplicitCaptures); 5768 Record->push_back(Lambda.HasKnownInternalLinkage); 5769 Record->push_back(Lambda.ManglingNumber); 5770 Record->push_back(D->getDeviceLambdaManglingNumber()); 5771 AddDeclRef(D->getLambdaContextDecl()); 5772 AddTypeSourceInfo(Lambda.MethodTyInfo); 5773 for (unsigned I = 0, N = Lambda.NumCaptures; I != N; ++I) { 5774 const LambdaCapture &Capture = Lambda.Captures[I]; 5775 AddSourceLocation(Capture.getLocation()); 5776 Record->push_back(Capture.isImplicit()); 5777 Record->push_back(Capture.getCaptureKind()); 5778 switch (Capture.getCaptureKind()) { 5779 case LCK_StarThis: 5780 case LCK_This: 5781 case LCK_VLAType: 5782 break; 5783 case LCK_ByCopy: 5784 case LCK_ByRef: 5785 VarDecl *Var = 5786 Capture.capturesVariable() ? Capture.getCapturedVar() : nullptr; 5787 AddDeclRef(Var); 5788 AddSourceLocation(Capture.isPackExpansion() ? Capture.getEllipsisLoc() 5789 : SourceLocation()); 5790 break; 5791 } 5792 } 5793 } 5794 } 5795 5796 void ASTRecordWriter::AddVarDeclInit(const VarDecl *VD) { 5797 const Expr *Init = VD->getInit(); 5798 if (!Init) { 5799 push_back(0); 5800 return; 5801 } 5802 5803 unsigned Val = 1; 5804 if (EvaluatedStmt *ES = VD->getEvaluatedStmt()) { 5805 Val |= (ES->HasConstantInitialization ? 2 : 0); 5806 Val |= (ES->HasConstantDestruction ? 4 : 0); 5807 // FIXME: Also emit the constant initializer value. 5808 } 5809 push_back(Val); 5810 writeStmtRef(Init); 5811 } 5812 5813 void ASTWriter::ReaderInitialized(ASTReader *Reader) { 5814 assert(Reader && "Cannot remove chain"); 5815 assert((!Chain || Chain == Reader) && "Cannot replace chain"); 5816 assert(FirstDeclID == NextDeclID && 5817 FirstTypeID == NextTypeID && 5818 FirstIdentID == NextIdentID && 5819 FirstMacroID == NextMacroID && 5820 FirstSubmoduleID == NextSubmoduleID && 5821 FirstSelectorID == NextSelectorID && 5822 "Setting chain after writing has started."); 5823 5824 Chain = Reader; 5825 5826 // Note, this will get called multiple times, once one the reader starts up 5827 // and again each time it's done reading a PCH or module. 5828 FirstDeclID = NUM_PREDEF_DECL_IDS + Chain->getTotalNumDecls(); 5829 FirstTypeID = NUM_PREDEF_TYPE_IDS + Chain->getTotalNumTypes(); 5830 FirstIdentID = NUM_PREDEF_IDENT_IDS + Chain->getTotalNumIdentifiers(); 5831 FirstMacroID = NUM_PREDEF_MACRO_IDS + Chain->getTotalNumMacros(); 5832 FirstSubmoduleID = NUM_PREDEF_SUBMODULE_IDS + Chain->getTotalNumSubmodules(); 5833 FirstSelectorID = NUM_PREDEF_SELECTOR_IDS + Chain->getTotalNumSelectors(); 5834 NextDeclID = FirstDeclID; 5835 NextTypeID = FirstTypeID; 5836 NextIdentID = FirstIdentID; 5837 NextMacroID = FirstMacroID; 5838 NextSelectorID = FirstSelectorID; 5839 NextSubmoduleID = FirstSubmoduleID; 5840 } 5841 5842 void ASTWriter::IdentifierRead(IdentID ID, IdentifierInfo *II) { 5843 // Always keep the highest ID. See \p TypeRead() for more information. 5844 IdentID &StoredID = IdentifierIDs[II]; 5845 if (ID > StoredID) 5846 StoredID = ID; 5847 } 5848 5849 void ASTWriter::MacroRead(serialization::MacroID ID, MacroInfo *MI) { 5850 // Always keep the highest ID. See \p TypeRead() for more information. 5851 MacroID &StoredID = MacroIDs[MI]; 5852 if (ID > StoredID) 5853 StoredID = ID; 5854 } 5855 5856 void ASTWriter::TypeRead(TypeIdx Idx, QualType T) { 5857 // Always take the highest-numbered type index. This copes with an interesting 5858 // case for chained AST writing where we schedule writing the type and then, 5859 // later, deserialize the type from another AST. In this case, we want to 5860 // keep the higher-numbered entry so that we can properly write it out to 5861 // the AST file. 5862 TypeIdx &StoredIdx = TypeIdxs[T]; 5863 if (Idx.getIndex() >= StoredIdx.getIndex()) 5864 StoredIdx = Idx; 5865 } 5866 5867 void ASTWriter::SelectorRead(SelectorID ID, Selector S) { 5868 // Always keep the highest ID. See \p TypeRead() for more information. 5869 SelectorID &StoredID = SelectorIDs[S]; 5870 if (ID > StoredID) 5871 StoredID = ID; 5872 } 5873 5874 void ASTWriter::MacroDefinitionRead(serialization::PreprocessedEntityID ID, 5875 MacroDefinitionRecord *MD) { 5876 assert(MacroDefinitions.find(MD) == MacroDefinitions.end()); 5877 MacroDefinitions[MD] = ID; 5878 } 5879 5880 void ASTWriter::ModuleRead(serialization::SubmoduleID ID, Module *Mod) { 5881 assert(SubmoduleIDs.find(Mod) == SubmoduleIDs.end()); 5882 SubmoduleIDs[Mod] = ID; 5883 } 5884 5885 void ASTWriter::CompletedTagDefinition(const TagDecl *D) { 5886 if (Chain && Chain->isProcessingUpdateRecords()) return; 5887 assert(D->isCompleteDefinition()); 5888 assert(!WritingAST && "Already writing the AST!"); 5889 if (auto *RD = dyn_cast<CXXRecordDecl>(D)) { 5890 // We are interested when a PCH decl is modified. 5891 if (RD->isFromASTFile()) { 5892 // A forward reference was mutated into a definition. Rewrite it. 5893 // FIXME: This happens during template instantiation, should we 5894 // have created a new definition decl instead ? 5895 assert(isTemplateInstantiation(RD->getTemplateSpecializationKind()) && 5896 "completed a tag from another module but not by instantiation?"); 5897 DeclUpdates[RD].push_back( 5898 DeclUpdate(UPD_CXX_INSTANTIATED_CLASS_DEFINITION)); 5899 } 5900 } 5901 } 5902 5903 static bool isImportedDeclContext(ASTReader *Chain, const Decl *D) { 5904 if (D->isFromASTFile()) 5905 return true; 5906 5907 // The predefined __va_list_tag struct is imported if we imported any decls. 5908 // FIXME: This is a gross hack. 5909 return D == D->getASTContext().getVaListTagDecl(); 5910 } 5911 5912 void ASTWriter::AddedVisibleDecl(const DeclContext *DC, const Decl *D) { 5913 if (Chain && Chain->isProcessingUpdateRecords()) return; 5914 assert(DC->isLookupContext() && 5915 "Should not add lookup results to non-lookup contexts!"); 5916 5917 // TU is handled elsewhere. 5918 if (isa<TranslationUnitDecl>(DC)) 5919 return; 5920 5921 // Namespaces are handled elsewhere, except for template instantiations of 5922 // FunctionTemplateDecls in namespaces. We are interested in cases where the 5923 // local instantiations are added to an imported context. Only happens when 5924 // adding ADL lookup candidates, for example templated friends. 5925 if (isa<NamespaceDecl>(DC) && D->getFriendObjectKind() == Decl::FOK_None && 5926 !isa<FunctionTemplateDecl>(D)) 5927 return; 5928 5929 // We're only interested in cases where a local declaration is added to an 5930 // imported context. 5931 if (D->isFromASTFile() || !isImportedDeclContext(Chain, cast<Decl>(DC))) 5932 return; 5933 5934 assert(DC == DC->getPrimaryContext() && "added to non-primary context"); 5935 assert(!getDefinitiveDeclContext(DC) && "DeclContext not definitive!"); 5936 assert(!WritingAST && "Already writing the AST!"); 5937 if (UpdatedDeclContexts.insert(DC) && !cast<Decl>(DC)->isFromASTFile()) { 5938 // We're adding a visible declaration to a predefined decl context. Ensure 5939 // that we write out all of its lookup results so we don't get a nasty 5940 // surprise when we try to emit its lookup table. 5941 llvm::append_range(DeclsToEmitEvenIfUnreferenced, DC->decls()); 5942 } 5943 DeclsToEmitEvenIfUnreferenced.push_back(D); 5944 } 5945 5946 void ASTWriter::AddedCXXImplicitMember(const CXXRecordDecl *RD, const Decl *D) { 5947 if (Chain && Chain->isProcessingUpdateRecords()) return; 5948 assert(D->isImplicit()); 5949 5950 // We're only interested in cases where a local declaration is added to an 5951 // imported context. 5952 if (D->isFromASTFile() || !isImportedDeclContext(Chain, RD)) 5953 return; 5954 5955 if (!isa<CXXMethodDecl>(D)) 5956 return; 5957 5958 // A decl coming from PCH was modified. 5959 assert(RD->isCompleteDefinition()); 5960 assert(!WritingAST && "Already writing the AST!"); 5961 DeclUpdates[RD].push_back(DeclUpdate(UPD_CXX_ADDED_IMPLICIT_MEMBER, D)); 5962 } 5963 5964 void ASTWriter::ResolvedExceptionSpec(const FunctionDecl *FD) { 5965 if (Chain && Chain->isProcessingUpdateRecords()) return; 5966 assert(!DoneWritingDeclsAndTypes && "Already done writing updates!"); 5967 if (!Chain) return; 5968 Chain->forEachImportedKeyDecl(FD, [&](const Decl *D) { 5969 // If we don't already know the exception specification for this redecl 5970 // chain, add an update record for it. 5971 if (isUnresolvedExceptionSpec(cast<FunctionDecl>(D) 5972 ->getType() 5973 ->castAs<FunctionProtoType>() 5974 ->getExceptionSpecType())) 5975 DeclUpdates[D].push_back(UPD_CXX_RESOLVED_EXCEPTION_SPEC); 5976 }); 5977 } 5978 5979 void ASTWriter::DeducedReturnType(const FunctionDecl *FD, QualType ReturnType) { 5980 if (Chain && Chain->isProcessingUpdateRecords()) return; 5981 assert(!WritingAST && "Already writing the AST!"); 5982 if (!Chain) return; 5983 Chain->forEachImportedKeyDecl(FD, [&](const Decl *D) { 5984 DeclUpdates[D].push_back( 5985 DeclUpdate(UPD_CXX_DEDUCED_RETURN_TYPE, ReturnType)); 5986 }); 5987 } 5988 5989 void ASTWriter::ResolvedOperatorDelete(const CXXDestructorDecl *DD, 5990 const FunctionDecl *Delete, 5991 Expr *ThisArg) { 5992 if (Chain && Chain->isProcessingUpdateRecords()) return; 5993 assert(!WritingAST && "Already writing the AST!"); 5994 assert(Delete && "Not given an operator delete"); 5995 if (!Chain) return; 5996 Chain->forEachImportedKeyDecl(DD, [&](const Decl *D) { 5997 DeclUpdates[D].push_back(DeclUpdate(UPD_CXX_RESOLVED_DTOR_DELETE, Delete)); 5998 }); 5999 } 6000 6001 void ASTWriter::CompletedImplicitDefinition(const FunctionDecl *D) { 6002 if (Chain && Chain->isProcessingUpdateRecords()) return; 6003 assert(!WritingAST && "Already writing the AST!"); 6004 if (!D->isFromASTFile()) 6005 return; // Declaration not imported from PCH. 6006 6007 // Implicit function decl from a PCH was defined. 6008 DeclUpdates[D].push_back(DeclUpdate(UPD_CXX_ADDED_FUNCTION_DEFINITION)); 6009 } 6010 6011 void ASTWriter::VariableDefinitionInstantiated(const VarDecl *D) { 6012 if (Chain && Chain->isProcessingUpdateRecords()) return; 6013 assert(!WritingAST && "Already writing the AST!"); 6014 if (!D->isFromASTFile()) 6015 return; 6016 6017 DeclUpdates[D].push_back(DeclUpdate(UPD_CXX_ADDED_VAR_DEFINITION)); 6018 } 6019 6020 void ASTWriter::FunctionDefinitionInstantiated(const FunctionDecl *D) { 6021 if (Chain && Chain->isProcessingUpdateRecords()) return; 6022 assert(!WritingAST && "Already writing the AST!"); 6023 if (!D->isFromASTFile()) 6024 return; 6025 6026 DeclUpdates[D].push_back(DeclUpdate(UPD_CXX_ADDED_FUNCTION_DEFINITION)); 6027 } 6028 6029 void ASTWriter::InstantiationRequested(const ValueDecl *D) { 6030 if (Chain && Chain->isProcessingUpdateRecords()) return; 6031 assert(!WritingAST && "Already writing the AST!"); 6032 if (!D->isFromASTFile()) 6033 return; 6034 6035 // Since the actual instantiation is delayed, this really means that we need 6036 // to update the instantiation location. 6037 SourceLocation POI; 6038 if (auto *VD = dyn_cast<VarDecl>(D)) 6039 POI = VD->getPointOfInstantiation(); 6040 else 6041 POI = cast<FunctionDecl>(D)->getPointOfInstantiation(); 6042 DeclUpdates[D].push_back(DeclUpdate(UPD_CXX_POINT_OF_INSTANTIATION, POI)); 6043 } 6044 6045 void ASTWriter::DefaultArgumentInstantiated(const ParmVarDecl *D) { 6046 if (Chain && Chain->isProcessingUpdateRecords()) return; 6047 assert(!WritingAST && "Already writing the AST!"); 6048 if (!D->isFromASTFile()) 6049 return; 6050 6051 DeclUpdates[D].push_back( 6052 DeclUpdate(UPD_CXX_INSTANTIATED_DEFAULT_ARGUMENT, D)); 6053 } 6054 6055 void ASTWriter::DefaultMemberInitializerInstantiated(const FieldDecl *D) { 6056 assert(!WritingAST && "Already writing the AST!"); 6057 if (!D->isFromASTFile()) 6058 return; 6059 6060 DeclUpdates[D].push_back( 6061 DeclUpdate(UPD_CXX_INSTANTIATED_DEFAULT_MEMBER_INITIALIZER, D)); 6062 } 6063 6064 void ASTWriter::AddedObjCCategoryToInterface(const ObjCCategoryDecl *CatD, 6065 const ObjCInterfaceDecl *IFD) { 6066 if (Chain && Chain->isProcessingUpdateRecords()) return; 6067 assert(!WritingAST && "Already writing the AST!"); 6068 if (!IFD->isFromASTFile()) 6069 return; // Declaration not imported from PCH. 6070 6071 assert(IFD->getDefinition() && "Category on a class without a definition?"); 6072 ObjCClassesWithCategories.insert( 6073 const_cast<ObjCInterfaceDecl *>(IFD->getDefinition())); 6074 } 6075 6076 void ASTWriter::DeclarationMarkedUsed(const Decl *D) { 6077 if (Chain && Chain->isProcessingUpdateRecords()) return; 6078 assert(!WritingAST && "Already writing the AST!"); 6079 6080 // If there is *any* declaration of the entity that's not from an AST file, 6081 // we can skip writing the update record. We make sure that isUsed() triggers 6082 // completion of the redeclaration chain of the entity. 6083 for (auto Prev = D->getMostRecentDecl(); Prev; Prev = Prev->getPreviousDecl()) 6084 if (IsLocalDecl(Prev)) 6085 return; 6086 6087 DeclUpdates[D].push_back(DeclUpdate(UPD_DECL_MARKED_USED)); 6088 } 6089 6090 void ASTWriter::DeclarationMarkedOpenMPThreadPrivate(const Decl *D) { 6091 if (Chain && Chain->isProcessingUpdateRecords()) return; 6092 assert(!WritingAST && "Already writing the AST!"); 6093 if (!D->isFromASTFile()) 6094 return; 6095 6096 DeclUpdates[D].push_back(DeclUpdate(UPD_DECL_MARKED_OPENMP_THREADPRIVATE)); 6097 } 6098 6099 void ASTWriter::DeclarationMarkedOpenMPAllocate(const Decl *D, const Attr *A) { 6100 if (Chain && Chain->isProcessingUpdateRecords()) return; 6101 assert(!WritingAST && "Already writing the AST!"); 6102 if (!D->isFromASTFile()) 6103 return; 6104 6105 DeclUpdates[D].push_back(DeclUpdate(UPD_DECL_MARKED_OPENMP_ALLOCATE, A)); 6106 } 6107 6108 void ASTWriter::DeclarationMarkedOpenMPDeclareTarget(const Decl *D, 6109 const Attr *Attr) { 6110 if (Chain && Chain->isProcessingUpdateRecords()) return; 6111 assert(!WritingAST && "Already writing the AST!"); 6112 if (!D->isFromASTFile()) 6113 return; 6114 6115 DeclUpdates[D].push_back( 6116 DeclUpdate(UPD_DECL_MARKED_OPENMP_DECLARETARGET, Attr)); 6117 } 6118 6119 void ASTWriter::RedefinedHiddenDefinition(const NamedDecl *D, Module *M) { 6120 if (Chain && Chain->isProcessingUpdateRecords()) return; 6121 assert(!WritingAST && "Already writing the AST!"); 6122 assert(!D->isUnconditionallyVisible() && "expected a hidden declaration"); 6123 DeclUpdates[D].push_back(DeclUpdate(UPD_DECL_EXPORTED, M)); 6124 } 6125 6126 void ASTWriter::AddedAttributeToRecord(const Attr *Attr, 6127 const RecordDecl *Record) { 6128 if (Chain && Chain->isProcessingUpdateRecords()) return; 6129 assert(!WritingAST && "Already writing the AST!"); 6130 if (!Record->isFromASTFile()) 6131 return; 6132 DeclUpdates[Record].push_back(DeclUpdate(UPD_ADDED_ATTR_TO_RECORD, Attr)); 6133 } 6134 6135 void ASTWriter::AddedCXXTemplateSpecialization( 6136 const ClassTemplateDecl *TD, const ClassTemplateSpecializationDecl *D) { 6137 assert(!WritingAST && "Already writing the AST!"); 6138 6139 if (!TD->getFirstDecl()->isFromASTFile()) 6140 return; 6141 if (Chain && Chain->isProcessingUpdateRecords()) 6142 return; 6143 6144 DeclsToEmitEvenIfUnreferenced.push_back(D); 6145 } 6146 6147 void ASTWriter::AddedCXXTemplateSpecialization( 6148 const VarTemplateDecl *TD, const VarTemplateSpecializationDecl *D) { 6149 assert(!WritingAST && "Already writing the AST!"); 6150 6151 if (!TD->getFirstDecl()->isFromASTFile()) 6152 return; 6153 if (Chain && Chain->isProcessingUpdateRecords()) 6154 return; 6155 6156 DeclsToEmitEvenIfUnreferenced.push_back(D); 6157 } 6158 6159 void ASTWriter::AddedCXXTemplateSpecialization(const FunctionTemplateDecl *TD, 6160 const FunctionDecl *D) { 6161 assert(!WritingAST && "Already writing the AST!"); 6162 6163 if (!TD->getFirstDecl()->isFromASTFile()) 6164 return; 6165 if (Chain && Chain->isProcessingUpdateRecords()) 6166 return; 6167 6168 DeclsToEmitEvenIfUnreferenced.push_back(D); 6169 } 6170 6171 //===----------------------------------------------------------------------===// 6172 //// OMPClause Serialization 6173 ////===----------------------------------------------------------------------===// 6174 6175 namespace { 6176 6177 class OMPClauseWriter : public OMPClauseVisitor<OMPClauseWriter> { 6178 ASTRecordWriter &Record; 6179 6180 public: 6181 OMPClauseWriter(ASTRecordWriter &Record) : Record(Record) {} 6182 #define GEN_CLANG_CLAUSE_CLASS 6183 #define CLAUSE_CLASS(Enum, Str, Class) void Visit##Class(Class *S); 6184 #include "llvm/Frontend/OpenMP/OMP.inc" 6185 void writeClause(OMPClause *C); 6186 void VisitOMPClauseWithPreInit(OMPClauseWithPreInit *C); 6187 void VisitOMPClauseWithPostUpdate(OMPClauseWithPostUpdate *C); 6188 }; 6189 6190 } 6191 6192 void ASTRecordWriter::writeOMPClause(OMPClause *C) { 6193 OMPClauseWriter(*this).writeClause(C); 6194 } 6195 6196 void OMPClauseWriter::writeClause(OMPClause *C) { 6197 Record.push_back(unsigned(C->getClauseKind())); 6198 Visit(C); 6199 Record.AddSourceLocation(C->getBeginLoc()); 6200 Record.AddSourceLocation(C->getEndLoc()); 6201 } 6202 6203 void OMPClauseWriter::VisitOMPClauseWithPreInit(OMPClauseWithPreInit *C) { 6204 Record.push_back(uint64_t(C->getCaptureRegion())); 6205 Record.AddStmt(C->getPreInitStmt()); 6206 } 6207 6208 void OMPClauseWriter::VisitOMPClauseWithPostUpdate(OMPClauseWithPostUpdate *C) { 6209 VisitOMPClauseWithPreInit(C); 6210 Record.AddStmt(C->getPostUpdateExpr()); 6211 } 6212 6213 void OMPClauseWriter::VisitOMPIfClause(OMPIfClause *C) { 6214 VisitOMPClauseWithPreInit(C); 6215 Record.push_back(uint64_t(C->getNameModifier())); 6216 Record.AddSourceLocation(C->getNameModifierLoc()); 6217 Record.AddSourceLocation(C->getColonLoc()); 6218 Record.AddStmt(C->getCondition()); 6219 Record.AddSourceLocation(C->getLParenLoc()); 6220 } 6221 6222 void OMPClauseWriter::VisitOMPFinalClause(OMPFinalClause *C) { 6223 VisitOMPClauseWithPreInit(C); 6224 Record.AddStmt(C->getCondition()); 6225 Record.AddSourceLocation(C->getLParenLoc()); 6226 } 6227 6228 void OMPClauseWriter::VisitOMPNumThreadsClause(OMPNumThreadsClause *C) { 6229 VisitOMPClauseWithPreInit(C); 6230 Record.AddStmt(C->getNumThreads()); 6231 Record.AddSourceLocation(C->getLParenLoc()); 6232 } 6233 6234 void OMPClauseWriter::VisitOMPSafelenClause(OMPSafelenClause *C) { 6235 Record.AddStmt(C->getSafelen()); 6236 Record.AddSourceLocation(C->getLParenLoc()); 6237 } 6238 6239 void OMPClauseWriter::VisitOMPSimdlenClause(OMPSimdlenClause *C) { 6240 Record.AddStmt(C->getSimdlen()); 6241 Record.AddSourceLocation(C->getLParenLoc()); 6242 } 6243 6244 void OMPClauseWriter::VisitOMPSizesClause(OMPSizesClause *C) { 6245 Record.push_back(C->getNumSizes()); 6246 for (Expr *Size : C->getSizesRefs()) 6247 Record.AddStmt(Size); 6248 Record.AddSourceLocation(C->getLParenLoc()); 6249 } 6250 6251 void OMPClauseWriter::VisitOMPFullClause(OMPFullClause *C) {} 6252 6253 void OMPClauseWriter::VisitOMPPartialClause(OMPPartialClause *C) { 6254 Record.AddStmt(C->getFactor()); 6255 Record.AddSourceLocation(C->getLParenLoc()); 6256 } 6257 6258 void OMPClauseWriter::VisitOMPAllocatorClause(OMPAllocatorClause *C) { 6259 Record.AddStmt(C->getAllocator()); 6260 Record.AddSourceLocation(C->getLParenLoc()); 6261 } 6262 6263 void OMPClauseWriter::VisitOMPCollapseClause(OMPCollapseClause *C) { 6264 Record.AddStmt(C->getNumForLoops()); 6265 Record.AddSourceLocation(C->getLParenLoc()); 6266 } 6267 6268 void OMPClauseWriter::VisitOMPDetachClause(OMPDetachClause *C) { 6269 Record.AddStmt(C->getEventHandler()); 6270 Record.AddSourceLocation(C->getLParenLoc()); 6271 } 6272 6273 void OMPClauseWriter::VisitOMPDefaultClause(OMPDefaultClause *C) { 6274 Record.push_back(unsigned(C->getDefaultKind())); 6275 Record.AddSourceLocation(C->getLParenLoc()); 6276 Record.AddSourceLocation(C->getDefaultKindKwLoc()); 6277 } 6278 6279 void OMPClauseWriter::VisitOMPProcBindClause(OMPProcBindClause *C) { 6280 Record.push_back(unsigned(C->getProcBindKind())); 6281 Record.AddSourceLocation(C->getLParenLoc()); 6282 Record.AddSourceLocation(C->getProcBindKindKwLoc()); 6283 } 6284 6285 void OMPClauseWriter::VisitOMPScheduleClause(OMPScheduleClause *C) { 6286 VisitOMPClauseWithPreInit(C); 6287 Record.push_back(C->getScheduleKind()); 6288 Record.push_back(C->getFirstScheduleModifier()); 6289 Record.push_back(C->getSecondScheduleModifier()); 6290 Record.AddStmt(C->getChunkSize()); 6291 Record.AddSourceLocation(C->getLParenLoc()); 6292 Record.AddSourceLocation(C->getFirstScheduleModifierLoc()); 6293 Record.AddSourceLocation(C->getSecondScheduleModifierLoc()); 6294 Record.AddSourceLocation(C->getScheduleKindLoc()); 6295 Record.AddSourceLocation(C->getCommaLoc()); 6296 } 6297 6298 void OMPClauseWriter::VisitOMPOrderedClause(OMPOrderedClause *C) { 6299 Record.push_back(C->getLoopNumIterations().size()); 6300 Record.AddStmt(C->getNumForLoops()); 6301 for (Expr *NumIter : C->getLoopNumIterations()) 6302 Record.AddStmt(NumIter); 6303 for (unsigned I = 0, E = C->getLoopNumIterations().size(); I <E; ++I) 6304 Record.AddStmt(C->getLoopCounter(I)); 6305 Record.AddSourceLocation(C->getLParenLoc()); 6306 } 6307 6308 void OMPClauseWriter::VisitOMPNowaitClause(OMPNowaitClause *) {} 6309 6310 void OMPClauseWriter::VisitOMPUntiedClause(OMPUntiedClause *) {} 6311 6312 void OMPClauseWriter::VisitOMPMergeableClause(OMPMergeableClause *) {} 6313 6314 void OMPClauseWriter::VisitOMPReadClause(OMPReadClause *) {} 6315 6316 void OMPClauseWriter::VisitOMPWriteClause(OMPWriteClause *) {} 6317 6318 void OMPClauseWriter::VisitOMPUpdateClause(OMPUpdateClause *C) { 6319 Record.push_back(C->isExtended() ? 1 : 0); 6320 if (C->isExtended()) { 6321 Record.AddSourceLocation(C->getLParenLoc()); 6322 Record.AddSourceLocation(C->getArgumentLoc()); 6323 Record.writeEnum(C->getDependencyKind()); 6324 } 6325 } 6326 6327 void OMPClauseWriter::VisitOMPCaptureClause(OMPCaptureClause *) {} 6328 6329 void OMPClauseWriter::VisitOMPCompareClause(OMPCompareClause *) {} 6330 6331 void OMPClauseWriter::VisitOMPSeqCstClause(OMPSeqCstClause *) {} 6332 6333 void OMPClauseWriter::VisitOMPAcqRelClause(OMPAcqRelClause *) {} 6334 6335 void OMPClauseWriter::VisitOMPAcquireClause(OMPAcquireClause *) {} 6336 6337 void OMPClauseWriter::VisitOMPReleaseClause(OMPReleaseClause *) {} 6338 6339 void OMPClauseWriter::VisitOMPRelaxedClause(OMPRelaxedClause *) {} 6340 6341 void OMPClauseWriter::VisitOMPThreadsClause(OMPThreadsClause *) {} 6342 6343 void OMPClauseWriter::VisitOMPSIMDClause(OMPSIMDClause *) {} 6344 6345 void OMPClauseWriter::VisitOMPNogroupClause(OMPNogroupClause *) {} 6346 6347 void OMPClauseWriter::VisitOMPInitClause(OMPInitClause *C) { 6348 Record.push_back(C->varlist_size()); 6349 for (Expr *VE : C->varlists()) 6350 Record.AddStmt(VE); 6351 Record.writeBool(C->getIsTarget()); 6352 Record.writeBool(C->getIsTargetSync()); 6353 Record.AddSourceLocation(C->getLParenLoc()); 6354 Record.AddSourceLocation(C->getVarLoc()); 6355 } 6356 6357 void OMPClauseWriter::VisitOMPUseClause(OMPUseClause *C) { 6358 Record.AddStmt(C->getInteropVar()); 6359 Record.AddSourceLocation(C->getLParenLoc()); 6360 Record.AddSourceLocation(C->getVarLoc()); 6361 } 6362 6363 void OMPClauseWriter::VisitOMPDestroyClause(OMPDestroyClause *C) { 6364 Record.AddStmt(C->getInteropVar()); 6365 Record.AddSourceLocation(C->getLParenLoc()); 6366 Record.AddSourceLocation(C->getVarLoc()); 6367 } 6368 6369 void OMPClauseWriter::VisitOMPNovariantsClause(OMPNovariantsClause *C) { 6370 VisitOMPClauseWithPreInit(C); 6371 Record.AddStmt(C->getCondition()); 6372 Record.AddSourceLocation(C->getLParenLoc()); 6373 } 6374 6375 void OMPClauseWriter::VisitOMPNocontextClause(OMPNocontextClause *C) { 6376 VisitOMPClauseWithPreInit(C); 6377 Record.AddStmt(C->getCondition()); 6378 Record.AddSourceLocation(C->getLParenLoc()); 6379 } 6380 6381 void OMPClauseWriter::VisitOMPFilterClause(OMPFilterClause *C) { 6382 VisitOMPClauseWithPreInit(C); 6383 Record.AddStmt(C->getThreadID()); 6384 Record.AddSourceLocation(C->getLParenLoc()); 6385 } 6386 6387 void OMPClauseWriter::VisitOMPAlignClause(OMPAlignClause *C) { 6388 Record.AddStmt(C->getAlignment()); 6389 Record.AddSourceLocation(C->getLParenLoc()); 6390 } 6391 6392 void OMPClauseWriter::VisitOMPPrivateClause(OMPPrivateClause *C) { 6393 Record.push_back(C->varlist_size()); 6394 Record.AddSourceLocation(C->getLParenLoc()); 6395 for (auto *VE : C->varlists()) { 6396 Record.AddStmt(VE); 6397 } 6398 for (auto *VE : C->private_copies()) { 6399 Record.AddStmt(VE); 6400 } 6401 } 6402 6403 void OMPClauseWriter::VisitOMPFirstprivateClause(OMPFirstprivateClause *C) { 6404 Record.push_back(C->varlist_size()); 6405 VisitOMPClauseWithPreInit(C); 6406 Record.AddSourceLocation(C->getLParenLoc()); 6407 for (auto *VE : C->varlists()) { 6408 Record.AddStmt(VE); 6409 } 6410 for (auto *VE : C->private_copies()) { 6411 Record.AddStmt(VE); 6412 } 6413 for (auto *VE : C->inits()) { 6414 Record.AddStmt(VE); 6415 } 6416 } 6417 6418 void OMPClauseWriter::VisitOMPLastprivateClause(OMPLastprivateClause *C) { 6419 Record.push_back(C->varlist_size()); 6420 VisitOMPClauseWithPostUpdate(C); 6421 Record.AddSourceLocation(C->getLParenLoc()); 6422 Record.writeEnum(C->getKind()); 6423 Record.AddSourceLocation(C->getKindLoc()); 6424 Record.AddSourceLocation(C->getColonLoc()); 6425 for (auto *VE : C->varlists()) 6426 Record.AddStmt(VE); 6427 for (auto *E : C->private_copies()) 6428 Record.AddStmt(E); 6429 for (auto *E : C->source_exprs()) 6430 Record.AddStmt(E); 6431 for (auto *E : C->destination_exprs()) 6432 Record.AddStmt(E); 6433 for (auto *E : C->assignment_ops()) 6434 Record.AddStmt(E); 6435 } 6436 6437 void OMPClauseWriter::VisitOMPSharedClause(OMPSharedClause *C) { 6438 Record.push_back(C->varlist_size()); 6439 Record.AddSourceLocation(C->getLParenLoc()); 6440 for (auto *VE : C->varlists()) 6441 Record.AddStmt(VE); 6442 } 6443 6444 void OMPClauseWriter::VisitOMPReductionClause(OMPReductionClause *C) { 6445 Record.push_back(C->varlist_size()); 6446 Record.writeEnum(C->getModifier()); 6447 VisitOMPClauseWithPostUpdate(C); 6448 Record.AddSourceLocation(C->getLParenLoc()); 6449 Record.AddSourceLocation(C->getModifierLoc()); 6450 Record.AddSourceLocation(C->getColonLoc()); 6451 Record.AddNestedNameSpecifierLoc(C->getQualifierLoc()); 6452 Record.AddDeclarationNameInfo(C->getNameInfo()); 6453 for (auto *VE : C->varlists()) 6454 Record.AddStmt(VE); 6455 for (auto *VE : C->privates()) 6456 Record.AddStmt(VE); 6457 for (auto *E : C->lhs_exprs()) 6458 Record.AddStmt(E); 6459 for (auto *E : C->rhs_exprs()) 6460 Record.AddStmt(E); 6461 for (auto *E : C->reduction_ops()) 6462 Record.AddStmt(E); 6463 if (C->getModifier() == clang::OMPC_REDUCTION_inscan) { 6464 for (auto *E : C->copy_ops()) 6465 Record.AddStmt(E); 6466 for (auto *E : C->copy_array_temps()) 6467 Record.AddStmt(E); 6468 for (auto *E : C->copy_array_elems()) 6469 Record.AddStmt(E); 6470 } 6471 } 6472 6473 void OMPClauseWriter::VisitOMPTaskReductionClause(OMPTaskReductionClause *C) { 6474 Record.push_back(C->varlist_size()); 6475 VisitOMPClauseWithPostUpdate(C); 6476 Record.AddSourceLocation(C->getLParenLoc()); 6477 Record.AddSourceLocation(C->getColonLoc()); 6478 Record.AddNestedNameSpecifierLoc(C->getQualifierLoc()); 6479 Record.AddDeclarationNameInfo(C->getNameInfo()); 6480 for (auto *VE : C->varlists()) 6481 Record.AddStmt(VE); 6482 for (auto *VE : C->privates()) 6483 Record.AddStmt(VE); 6484 for (auto *E : C->lhs_exprs()) 6485 Record.AddStmt(E); 6486 for (auto *E : C->rhs_exprs()) 6487 Record.AddStmt(E); 6488 for (auto *E : C->reduction_ops()) 6489 Record.AddStmt(E); 6490 } 6491 6492 void OMPClauseWriter::VisitOMPInReductionClause(OMPInReductionClause *C) { 6493 Record.push_back(C->varlist_size()); 6494 VisitOMPClauseWithPostUpdate(C); 6495 Record.AddSourceLocation(C->getLParenLoc()); 6496 Record.AddSourceLocation(C->getColonLoc()); 6497 Record.AddNestedNameSpecifierLoc(C->getQualifierLoc()); 6498 Record.AddDeclarationNameInfo(C->getNameInfo()); 6499 for (auto *VE : C->varlists()) 6500 Record.AddStmt(VE); 6501 for (auto *VE : C->privates()) 6502 Record.AddStmt(VE); 6503 for (auto *E : C->lhs_exprs()) 6504 Record.AddStmt(E); 6505 for (auto *E : C->rhs_exprs()) 6506 Record.AddStmt(E); 6507 for (auto *E : C->reduction_ops()) 6508 Record.AddStmt(E); 6509 for (auto *E : C->taskgroup_descriptors()) 6510 Record.AddStmt(E); 6511 } 6512 6513 void OMPClauseWriter::VisitOMPLinearClause(OMPLinearClause *C) { 6514 Record.push_back(C->varlist_size()); 6515 VisitOMPClauseWithPostUpdate(C); 6516 Record.AddSourceLocation(C->getLParenLoc()); 6517 Record.AddSourceLocation(C->getColonLoc()); 6518 Record.push_back(C->getModifier()); 6519 Record.AddSourceLocation(C->getModifierLoc()); 6520 for (auto *VE : C->varlists()) { 6521 Record.AddStmt(VE); 6522 } 6523 for (auto *VE : C->privates()) { 6524 Record.AddStmt(VE); 6525 } 6526 for (auto *VE : C->inits()) { 6527 Record.AddStmt(VE); 6528 } 6529 for (auto *VE : C->updates()) { 6530 Record.AddStmt(VE); 6531 } 6532 for (auto *VE : C->finals()) { 6533 Record.AddStmt(VE); 6534 } 6535 Record.AddStmt(C->getStep()); 6536 Record.AddStmt(C->getCalcStep()); 6537 for (auto *VE : C->used_expressions()) 6538 Record.AddStmt(VE); 6539 } 6540 6541 void OMPClauseWriter::VisitOMPAlignedClause(OMPAlignedClause *C) { 6542 Record.push_back(C->varlist_size()); 6543 Record.AddSourceLocation(C->getLParenLoc()); 6544 Record.AddSourceLocation(C->getColonLoc()); 6545 for (auto *VE : C->varlists()) 6546 Record.AddStmt(VE); 6547 Record.AddStmt(C->getAlignment()); 6548 } 6549 6550 void OMPClauseWriter::VisitOMPCopyinClause(OMPCopyinClause *C) { 6551 Record.push_back(C->varlist_size()); 6552 Record.AddSourceLocation(C->getLParenLoc()); 6553 for (auto *VE : C->varlists()) 6554 Record.AddStmt(VE); 6555 for (auto *E : C->source_exprs()) 6556 Record.AddStmt(E); 6557 for (auto *E : C->destination_exprs()) 6558 Record.AddStmt(E); 6559 for (auto *E : C->assignment_ops()) 6560 Record.AddStmt(E); 6561 } 6562 6563 void OMPClauseWriter::VisitOMPCopyprivateClause(OMPCopyprivateClause *C) { 6564 Record.push_back(C->varlist_size()); 6565 Record.AddSourceLocation(C->getLParenLoc()); 6566 for (auto *VE : C->varlists()) 6567 Record.AddStmt(VE); 6568 for (auto *E : C->source_exprs()) 6569 Record.AddStmt(E); 6570 for (auto *E : C->destination_exprs()) 6571 Record.AddStmt(E); 6572 for (auto *E : C->assignment_ops()) 6573 Record.AddStmt(E); 6574 } 6575 6576 void OMPClauseWriter::VisitOMPFlushClause(OMPFlushClause *C) { 6577 Record.push_back(C->varlist_size()); 6578 Record.AddSourceLocation(C->getLParenLoc()); 6579 for (auto *VE : C->varlists()) 6580 Record.AddStmt(VE); 6581 } 6582 6583 void OMPClauseWriter::VisitOMPDepobjClause(OMPDepobjClause *C) { 6584 Record.AddStmt(C->getDepobj()); 6585 Record.AddSourceLocation(C->getLParenLoc()); 6586 } 6587 6588 void OMPClauseWriter::VisitOMPDependClause(OMPDependClause *C) { 6589 Record.push_back(C->varlist_size()); 6590 Record.push_back(C->getNumLoops()); 6591 Record.AddSourceLocation(C->getLParenLoc()); 6592 Record.AddStmt(C->getModifier()); 6593 Record.push_back(C->getDependencyKind()); 6594 Record.AddSourceLocation(C->getDependencyLoc()); 6595 Record.AddSourceLocation(C->getColonLoc()); 6596 Record.AddSourceLocation(C->getOmpAllMemoryLoc()); 6597 for (auto *VE : C->varlists()) 6598 Record.AddStmt(VE); 6599 for (unsigned I = 0, E = C->getNumLoops(); I < E; ++I) 6600 Record.AddStmt(C->getLoopData(I)); 6601 } 6602 6603 void OMPClauseWriter::VisitOMPDeviceClause(OMPDeviceClause *C) { 6604 VisitOMPClauseWithPreInit(C); 6605 Record.writeEnum(C->getModifier()); 6606 Record.AddStmt(C->getDevice()); 6607 Record.AddSourceLocation(C->getModifierLoc()); 6608 Record.AddSourceLocation(C->getLParenLoc()); 6609 } 6610 6611 void OMPClauseWriter::VisitOMPMapClause(OMPMapClause *C) { 6612 Record.push_back(C->varlist_size()); 6613 Record.push_back(C->getUniqueDeclarationsNum()); 6614 Record.push_back(C->getTotalComponentListNum()); 6615 Record.push_back(C->getTotalComponentsNum()); 6616 Record.AddSourceLocation(C->getLParenLoc()); 6617 for (unsigned I = 0; I < NumberOfOMPMapClauseModifiers; ++I) { 6618 Record.push_back(C->getMapTypeModifier(I)); 6619 Record.AddSourceLocation(C->getMapTypeModifierLoc(I)); 6620 } 6621 Record.AddNestedNameSpecifierLoc(C->getMapperQualifierLoc()); 6622 Record.AddDeclarationNameInfo(C->getMapperIdInfo()); 6623 Record.push_back(C->getMapType()); 6624 Record.AddSourceLocation(C->getMapLoc()); 6625 Record.AddSourceLocation(C->getColonLoc()); 6626 for (auto *E : C->varlists()) 6627 Record.AddStmt(E); 6628 for (auto *E : C->mapperlists()) 6629 Record.AddStmt(E); 6630 for (auto *D : C->all_decls()) 6631 Record.AddDeclRef(D); 6632 for (auto N : C->all_num_lists()) 6633 Record.push_back(N); 6634 for (auto N : C->all_lists_sizes()) 6635 Record.push_back(N); 6636 for (auto &M : C->all_components()) { 6637 Record.AddStmt(M.getAssociatedExpression()); 6638 Record.AddDeclRef(M.getAssociatedDeclaration()); 6639 } 6640 } 6641 6642 void OMPClauseWriter::VisitOMPAllocateClause(OMPAllocateClause *C) { 6643 Record.push_back(C->varlist_size()); 6644 Record.AddSourceLocation(C->getLParenLoc()); 6645 Record.AddSourceLocation(C->getColonLoc()); 6646 Record.AddStmt(C->getAllocator()); 6647 for (auto *VE : C->varlists()) 6648 Record.AddStmt(VE); 6649 } 6650 6651 void OMPClauseWriter::VisitOMPNumTeamsClause(OMPNumTeamsClause *C) { 6652 VisitOMPClauseWithPreInit(C); 6653 Record.AddStmt(C->getNumTeams()); 6654 Record.AddSourceLocation(C->getLParenLoc()); 6655 } 6656 6657 void OMPClauseWriter::VisitOMPThreadLimitClause(OMPThreadLimitClause *C) { 6658 VisitOMPClauseWithPreInit(C); 6659 Record.AddStmt(C->getThreadLimit()); 6660 Record.AddSourceLocation(C->getLParenLoc()); 6661 } 6662 6663 void OMPClauseWriter::VisitOMPPriorityClause(OMPPriorityClause *C) { 6664 VisitOMPClauseWithPreInit(C); 6665 Record.AddStmt(C->getPriority()); 6666 Record.AddSourceLocation(C->getLParenLoc()); 6667 } 6668 6669 void OMPClauseWriter::VisitOMPGrainsizeClause(OMPGrainsizeClause *C) { 6670 VisitOMPClauseWithPreInit(C); 6671 Record.AddStmt(C->getGrainsize()); 6672 Record.AddSourceLocation(C->getLParenLoc()); 6673 } 6674 6675 void OMPClauseWriter::VisitOMPNumTasksClause(OMPNumTasksClause *C) { 6676 VisitOMPClauseWithPreInit(C); 6677 Record.AddStmt(C->getNumTasks()); 6678 Record.AddSourceLocation(C->getLParenLoc()); 6679 } 6680 6681 void OMPClauseWriter::VisitOMPHintClause(OMPHintClause *C) { 6682 Record.AddStmt(C->getHint()); 6683 Record.AddSourceLocation(C->getLParenLoc()); 6684 } 6685 6686 void OMPClauseWriter::VisitOMPDistScheduleClause(OMPDistScheduleClause *C) { 6687 VisitOMPClauseWithPreInit(C); 6688 Record.push_back(C->getDistScheduleKind()); 6689 Record.AddStmt(C->getChunkSize()); 6690 Record.AddSourceLocation(C->getLParenLoc()); 6691 Record.AddSourceLocation(C->getDistScheduleKindLoc()); 6692 Record.AddSourceLocation(C->getCommaLoc()); 6693 } 6694 6695 void OMPClauseWriter::VisitOMPDefaultmapClause(OMPDefaultmapClause *C) { 6696 Record.push_back(C->getDefaultmapKind()); 6697 Record.push_back(C->getDefaultmapModifier()); 6698 Record.AddSourceLocation(C->getLParenLoc()); 6699 Record.AddSourceLocation(C->getDefaultmapModifierLoc()); 6700 Record.AddSourceLocation(C->getDefaultmapKindLoc()); 6701 } 6702 6703 void OMPClauseWriter::VisitOMPToClause(OMPToClause *C) { 6704 Record.push_back(C->varlist_size()); 6705 Record.push_back(C->getUniqueDeclarationsNum()); 6706 Record.push_back(C->getTotalComponentListNum()); 6707 Record.push_back(C->getTotalComponentsNum()); 6708 Record.AddSourceLocation(C->getLParenLoc()); 6709 for (unsigned I = 0; I < NumberOfOMPMotionModifiers; ++I) { 6710 Record.push_back(C->getMotionModifier(I)); 6711 Record.AddSourceLocation(C->getMotionModifierLoc(I)); 6712 } 6713 Record.AddNestedNameSpecifierLoc(C->getMapperQualifierLoc()); 6714 Record.AddDeclarationNameInfo(C->getMapperIdInfo()); 6715 Record.AddSourceLocation(C->getColonLoc()); 6716 for (auto *E : C->varlists()) 6717 Record.AddStmt(E); 6718 for (auto *E : C->mapperlists()) 6719 Record.AddStmt(E); 6720 for (auto *D : C->all_decls()) 6721 Record.AddDeclRef(D); 6722 for (auto N : C->all_num_lists()) 6723 Record.push_back(N); 6724 for (auto N : C->all_lists_sizes()) 6725 Record.push_back(N); 6726 for (auto &M : C->all_components()) { 6727 Record.AddStmt(M.getAssociatedExpression()); 6728 Record.writeBool(M.isNonContiguous()); 6729 Record.AddDeclRef(M.getAssociatedDeclaration()); 6730 } 6731 } 6732 6733 void OMPClauseWriter::VisitOMPFromClause(OMPFromClause *C) { 6734 Record.push_back(C->varlist_size()); 6735 Record.push_back(C->getUniqueDeclarationsNum()); 6736 Record.push_back(C->getTotalComponentListNum()); 6737 Record.push_back(C->getTotalComponentsNum()); 6738 Record.AddSourceLocation(C->getLParenLoc()); 6739 for (unsigned I = 0; I < NumberOfOMPMotionModifiers; ++I) { 6740 Record.push_back(C->getMotionModifier(I)); 6741 Record.AddSourceLocation(C->getMotionModifierLoc(I)); 6742 } 6743 Record.AddNestedNameSpecifierLoc(C->getMapperQualifierLoc()); 6744 Record.AddDeclarationNameInfo(C->getMapperIdInfo()); 6745 Record.AddSourceLocation(C->getColonLoc()); 6746 for (auto *E : C->varlists()) 6747 Record.AddStmt(E); 6748 for (auto *E : C->mapperlists()) 6749 Record.AddStmt(E); 6750 for (auto *D : C->all_decls()) 6751 Record.AddDeclRef(D); 6752 for (auto N : C->all_num_lists()) 6753 Record.push_back(N); 6754 for (auto N : C->all_lists_sizes()) 6755 Record.push_back(N); 6756 for (auto &M : C->all_components()) { 6757 Record.AddStmt(M.getAssociatedExpression()); 6758 Record.writeBool(M.isNonContiguous()); 6759 Record.AddDeclRef(M.getAssociatedDeclaration()); 6760 } 6761 } 6762 6763 void OMPClauseWriter::VisitOMPUseDevicePtrClause(OMPUseDevicePtrClause *C) { 6764 Record.push_back(C->varlist_size()); 6765 Record.push_back(C->getUniqueDeclarationsNum()); 6766 Record.push_back(C->getTotalComponentListNum()); 6767 Record.push_back(C->getTotalComponentsNum()); 6768 Record.AddSourceLocation(C->getLParenLoc()); 6769 for (auto *E : C->varlists()) 6770 Record.AddStmt(E); 6771 for (auto *VE : C->private_copies()) 6772 Record.AddStmt(VE); 6773 for (auto *VE : C->inits()) 6774 Record.AddStmt(VE); 6775 for (auto *D : C->all_decls()) 6776 Record.AddDeclRef(D); 6777 for (auto N : C->all_num_lists()) 6778 Record.push_back(N); 6779 for (auto N : C->all_lists_sizes()) 6780 Record.push_back(N); 6781 for (auto &M : C->all_components()) { 6782 Record.AddStmt(M.getAssociatedExpression()); 6783 Record.AddDeclRef(M.getAssociatedDeclaration()); 6784 } 6785 } 6786 6787 void OMPClauseWriter::VisitOMPUseDeviceAddrClause(OMPUseDeviceAddrClause *C) { 6788 Record.push_back(C->varlist_size()); 6789 Record.push_back(C->getUniqueDeclarationsNum()); 6790 Record.push_back(C->getTotalComponentListNum()); 6791 Record.push_back(C->getTotalComponentsNum()); 6792 Record.AddSourceLocation(C->getLParenLoc()); 6793 for (auto *E : C->varlists()) 6794 Record.AddStmt(E); 6795 for (auto *D : C->all_decls()) 6796 Record.AddDeclRef(D); 6797 for (auto N : C->all_num_lists()) 6798 Record.push_back(N); 6799 for (auto N : C->all_lists_sizes()) 6800 Record.push_back(N); 6801 for (auto &M : C->all_components()) { 6802 Record.AddStmt(M.getAssociatedExpression()); 6803 Record.AddDeclRef(M.getAssociatedDeclaration()); 6804 } 6805 } 6806 6807 void OMPClauseWriter::VisitOMPIsDevicePtrClause(OMPIsDevicePtrClause *C) { 6808 Record.push_back(C->varlist_size()); 6809 Record.push_back(C->getUniqueDeclarationsNum()); 6810 Record.push_back(C->getTotalComponentListNum()); 6811 Record.push_back(C->getTotalComponentsNum()); 6812 Record.AddSourceLocation(C->getLParenLoc()); 6813 for (auto *E : C->varlists()) 6814 Record.AddStmt(E); 6815 for (auto *D : C->all_decls()) 6816 Record.AddDeclRef(D); 6817 for (auto N : C->all_num_lists()) 6818 Record.push_back(N); 6819 for (auto N : C->all_lists_sizes()) 6820 Record.push_back(N); 6821 for (auto &M : C->all_components()) { 6822 Record.AddStmt(M.getAssociatedExpression()); 6823 Record.AddDeclRef(M.getAssociatedDeclaration()); 6824 } 6825 } 6826 6827 void OMPClauseWriter::VisitOMPHasDeviceAddrClause(OMPHasDeviceAddrClause *C) { 6828 Record.push_back(C->varlist_size()); 6829 Record.push_back(C->getUniqueDeclarationsNum()); 6830 Record.push_back(C->getTotalComponentListNum()); 6831 Record.push_back(C->getTotalComponentsNum()); 6832 Record.AddSourceLocation(C->getLParenLoc()); 6833 for (auto *E : C->varlists()) 6834 Record.AddStmt(E); 6835 for (auto *D : C->all_decls()) 6836 Record.AddDeclRef(D); 6837 for (auto N : C->all_num_lists()) 6838 Record.push_back(N); 6839 for (auto N : C->all_lists_sizes()) 6840 Record.push_back(N); 6841 for (auto &M : C->all_components()) { 6842 Record.AddStmt(M.getAssociatedExpression()); 6843 Record.AddDeclRef(M.getAssociatedDeclaration()); 6844 } 6845 } 6846 6847 void OMPClauseWriter::VisitOMPUnifiedAddressClause(OMPUnifiedAddressClause *) {} 6848 6849 void OMPClauseWriter::VisitOMPUnifiedSharedMemoryClause( 6850 OMPUnifiedSharedMemoryClause *) {} 6851 6852 void OMPClauseWriter::VisitOMPReverseOffloadClause(OMPReverseOffloadClause *) {} 6853 6854 void 6855 OMPClauseWriter::VisitOMPDynamicAllocatorsClause(OMPDynamicAllocatorsClause *) { 6856 } 6857 6858 void OMPClauseWriter::VisitOMPAtomicDefaultMemOrderClause( 6859 OMPAtomicDefaultMemOrderClause *C) { 6860 Record.push_back(C->getAtomicDefaultMemOrderKind()); 6861 Record.AddSourceLocation(C->getLParenLoc()); 6862 Record.AddSourceLocation(C->getAtomicDefaultMemOrderKindKwLoc()); 6863 } 6864 6865 void OMPClauseWriter::VisitOMPNontemporalClause(OMPNontemporalClause *C) { 6866 Record.push_back(C->varlist_size()); 6867 Record.AddSourceLocation(C->getLParenLoc()); 6868 for (auto *VE : C->varlists()) 6869 Record.AddStmt(VE); 6870 for (auto *E : C->private_refs()) 6871 Record.AddStmt(E); 6872 } 6873 6874 void OMPClauseWriter::VisitOMPInclusiveClause(OMPInclusiveClause *C) { 6875 Record.push_back(C->varlist_size()); 6876 Record.AddSourceLocation(C->getLParenLoc()); 6877 for (auto *VE : C->varlists()) 6878 Record.AddStmt(VE); 6879 } 6880 6881 void OMPClauseWriter::VisitOMPExclusiveClause(OMPExclusiveClause *C) { 6882 Record.push_back(C->varlist_size()); 6883 Record.AddSourceLocation(C->getLParenLoc()); 6884 for (auto *VE : C->varlists()) 6885 Record.AddStmt(VE); 6886 } 6887 6888 void OMPClauseWriter::VisitOMPOrderClause(OMPOrderClause *C) { 6889 Record.writeEnum(C->getKind()); 6890 Record.AddSourceLocation(C->getLParenLoc()); 6891 Record.AddSourceLocation(C->getKindKwLoc()); 6892 } 6893 6894 void OMPClauseWriter::VisitOMPUsesAllocatorsClause(OMPUsesAllocatorsClause *C) { 6895 Record.push_back(C->getNumberOfAllocators()); 6896 Record.AddSourceLocation(C->getLParenLoc()); 6897 for (unsigned I = 0, E = C->getNumberOfAllocators(); I < E; ++I) { 6898 OMPUsesAllocatorsClause::Data Data = C->getAllocatorData(I); 6899 Record.AddStmt(Data.Allocator); 6900 Record.AddStmt(Data.AllocatorTraits); 6901 Record.AddSourceLocation(Data.LParenLoc); 6902 Record.AddSourceLocation(Data.RParenLoc); 6903 } 6904 } 6905 6906 void OMPClauseWriter::VisitOMPAffinityClause(OMPAffinityClause *C) { 6907 Record.push_back(C->varlist_size()); 6908 Record.AddSourceLocation(C->getLParenLoc()); 6909 Record.AddStmt(C->getModifier()); 6910 Record.AddSourceLocation(C->getColonLoc()); 6911 for (Expr *E : C->varlists()) 6912 Record.AddStmt(E); 6913 } 6914 6915 void OMPClauseWriter::VisitOMPBindClause(OMPBindClause *C) { 6916 Record.writeEnum(C->getBindKind()); 6917 Record.AddSourceLocation(C->getLParenLoc()); 6918 Record.AddSourceLocation(C->getBindKindLoc()); 6919 } 6920 6921 void ASTRecordWriter::writeOMPTraitInfo(const OMPTraitInfo *TI) { 6922 writeUInt32(TI->Sets.size()); 6923 for (const auto &Set : TI->Sets) { 6924 writeEnum(Set.Kind); 6925 writeUInt32(Set.Selectors.size()); 6926 for (const auto &Selector : Set.Selectors) { 6927 writeEnum(Selector.Kind); 6928 writeBool(Selector.ScoreOrCondition); 6929 if (Selector.ScoreOrCondition) 6930 writeExprRef(Selector.ScoreOrCondition); 6931 writeUInt32(Selector.Properties.size()); 6932 for (const auto &Property : Selector.Properties) 6933 writeEnum(Property.Kind); 6934 } 6935 } 6936 } 6937 6938 void ASTRecordWriter::writeOMPChildren(OMPChildren *Data) { 6939 if (!Data) 6940 return; 6941 writeUInt32(Data->getNumClauses()); 6942 writeUInt32(Data->getNumChildren()); 6943 writeBool(Data->hasAssociatedStmt()); 6944 for (unsigned I = 0, E = Data->getNumClauses(); I < E; ++I) 6945 writeOMPClause(Data->getClauses()[I]); 6946 if (Data->hasAssociatedStmt()) 6947 AddStmt(Data->getAssociatedStmt()); 6948 for (unsigned I = 0, E = Data->getNumChildren(); I < E; ++I) 6949 AddStmt(Data->getChildren()[I]); 6950 } 6951