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