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