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