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