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