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