clang API Documentation
00001 //===--- ASTWriter.cpp - AST File Writer ----------------------------------===// 00002 // 00003 // The LLVM Compiler Infrastructure 00004 // 00005 // This file is distributed under the University of Illinois Open Source 00006 // License. See LICENSE.TXT for details. 00007 // 00008 //===----------------------------------------------------------------------===// 00009 // 00010 // This file defines the ASTWriter class, which writes AST files. 00011 // 00012 //===----------------------------------------------------------------------===// 00013 00014 #include "clang/Serialization/ASTWriter.h" 00015 #include "ASTCommon.h" 00016 #include "clang/AST/ASTContext.h" 00017 #include "clang/AST/Decl.h" 00018 #include "clang/AST/DeclContextInternals.h" 00019 #include "clang/AST/DeclFriend.h" 00020 #include "clang/AST/DeclLookups.h" 00021 #include "clang/AST/DeclTemplate.h" 00022 #include "clang/AST/Expr.h" 00023 #include "clang/AST/ExprCXX.h" 00024 #include "clang/AST/Type.h" 00025 #include "clang/AST/TypeLocVisitor.h" 00026 #include "clang/Basic/DiagnosticOptions.h" 00027 #include "clang/Basic/FileManager.h" 00028 #include "clang/Basic/FileSystemStatCache.h" 00029 #include "clang/Basic/SourceManager.h" 00030 #include "clang/Basic/SourceManagerInternals.h" 00031 #include "clang/Basic/TargetInfo.h" 00032 #include "clang/Basic/TargetOptions.h" 00033 #include "clang/Basic/Version.h" 00034 #include "clang/Basic/VersionTuple.h" 00035 #include "clang/Lex/HeaderSearch.h" 00036 #include "clang/Lex/HeaderSearchOptions.h" 00037 #include "clang/Lex/MacroInfo.h" 00038 #include "clang/Lex/PreprocessingRecord.h" 00039 #include "clang/Lex/Preprocessor.h" 00040 #include "clang/Lex/PreprocessorOptions.h" 00041 #include "clang/Sema/IdentifierResolver.h" 00042 #include "clang/Sema/Sema.h" 00043 #include "clang/Serialization/ASTReader.h" 00044 #include "llvm/ADT/APFloat.h" 00045 #include "llvm/ADT/APInt.h" 00046 #include "llvm/ADT/Hashing.h" 00047 #include "llvm/ADT/StringExtras.h" 00048 #include "llvm/Bitcode/BitstreamWriter.h" 00049 #include "llvm/Support/EndianStream.h" 00050 #include "llvm/Support/FileSystem.h" 00051 #include "llvm/Support/MemoryBuffer.h" 00052 #include "llvm/Support/OnDiskHashTable.h" 00053 #include "llvm/Support/Path.h" 00054 #include "llvm/Support/Process.h" 00055 #include <algorithm> 00056 #include <cstdio> 00057 #include <string.h> 00058 #include <utility> 00059 using namespace clang; 00060 using namespace clang::serialization; 00061 00062 template <typename T, typename Allocator> 00063 static StringRef data(const std::vector<T, Allocator> &v) { 00064 if (v.empty()) return StringRef(); 00065 return StringRef(reinterpret_cast<const char*>(&v[0]), 00066 sizeof(T) * v.size()); 00067 } 00068 00069 template <typename T> 00070 static StringRef data(const SmallVectorImpl<T> &v) { 00071 return StringRef(reinterpret_cast<const char*>(v.data()), 00072 sizeof(T) * v.size()); 00073 } 00074 00075 //===----------------------------------------------------------------------===// 00076 // Type serialization 00077 //===----------------------------------------------------------------------===// 00078 00079 namespace { 00080 class ASTTypeWriter { 00081 ASTWriter &Writer; 00082 ASTWriter::RecordDataImpl &Record; 00083 00084 public: 00085 /// \brief Type code that corresponds to the record generated. 00086 TypeCode Code; 00087 /// \brief Abbreviation to use for the record, if any. 00088 unsigned AbbrevToUse; 00089 00090 ASTTypeWriter(ASTWriter &Writer, ASTWriter::RecordDataImpl &Record) 00091 : Writer(Writer), Record(Record), Code(TYPE_EXT_QUAL) { } 00092 00093 void VisitArrayType(const ArrayType *T); 00094 void VisitFunctionType(const FunctionType *T); 00095 void VisitTagType(const TagType *T); 00096 00097 #define TYPE(Class, Base) void Visit##Class##Type(const Class##Type *T); 00098 #define ABSTRACT_TYPE(Class, Base) 00099 #include "clang/AST/TypeNodes.def" 00100 }; 00101 } 00102 00103 void ASTTypeWriter::VisitBuiltinType(const BuiltinType *T) { 00104 llvm_unreachable("Built-in types are never serialized"); 00105 } 00106 00107 void ASTTypeWriter::VisitComplexType(const ComplexType *T) { 00108 Writer.AddTypeRef(T->getElementType(), Record); 00109 Code = TYPE_COMPLEX; 00110 } 00111 00112 void ASTTypeWriter::VisitPointerType(const PointerType *T) { 00113 Writer.AddTypeRef(T->getPointeeType(), Record); 00114 Code = TYPE_POINTER; 00115 } 00116 00117 void ASTTypeWriter::VisitDecayedType(const DecayedType *T) { 00118 Writer.AddTypeRef(T->getOriginalType(), Record); 00119 Code = TYPE_DECAYED; 00120 } 00121 00122 void ASTTypeWriter::VisitAdjustedType(const AdjustedType *T) { 00123 Writer.AddTypeRef(T->getOriginalType(), Record); 00124 Writer.AddTypeRef(T->getAdjustedType(), Record); 00125 Code = TYPE_ADJUSTED; 00126 } 00127 00128 void ASTTypeWriter::VisitBlockPointerType(const BlockPointerType *T) { 00129 Writer.AddTypeRef(T->getPointeeType(), Record); 00130 Code = TYPE_BLOCK_POINTER; 00131 } 00132 00133 void ASTTypeWriter::VisitLValueReferenceType(const LValueReferenceType *T) { 00134 Writer.AddTypeRef(T->getPointeeTypeAsWritten(), Record); 00135 Record.push_back(T->isSpelledAsLValue()); 00136 Code = TYPE_LVALUE_REFERENCE; 00137 } 00138 00139 void ASTTypeWriter::VisitRValueReferenceType(const RValueReferenceType *T) { 00140 Writer.AddTypeRef(T->getPointeeTypeAsWritten(), Record); 00141 Code = TYPE_RVALUE_REFERENCE; 00142 } 00143 00144 void ASTTypeWriter::VisitMemberPointerType(const MemberPointerType *T) { 00145 Writer.AddTypeRef(T->getPointeeType(), Record); 00146 Writer.AddTypeRef(QualType(T->getClass(), 0), Record); 00147 Code = TYPE_MEMBER_POINTER; 00148 } 00149 00150 void ASTTypeWriter::VisitArrayType(const ArrayType *T) { 00151 Writer.AddTypeRef(T->getElementType(), Record); 00152 Record.push_back(T->getSizeModifier()); // FIXME: stable values 00153 Record.push_back(T->getIndexTypeCVRQualifiers()); // FIXME: stable values 00154 } 00155 00156 void ASTTypeWriter::VisitConstantArrayType(const ConstantArrayType *T) { 00157 VisitArrayType(T); 00158 Writer.AddAPInt(T->getSize(), Record); 00159 Code = TYPE_CONSTANT_ARRAY; 00160 } 00161 00162 void ASTTypeWriter::VisitIncompleteArrayType(const IncompleteArrayType *T) { 00163 VisitArrayType(T); 00164 Code = TYPE_INCOMPLETE_ARRAY; 00165 } 00166 00167 void ASTTypeWriter::VisitVariableArrayType(const VariableArrayType *T) { 00168 VisitArrayType(T); 00169 Writer.AddSourceLocation(T->getLBracketLoc(), Record); 00170 Writer.AddSourceLocation(T->getRBracketLoc(), Record); 00171 Writer.AddStmt(T->getSizeExpr()); 00172 Code = TYPE_VARIABLE_ARRAY; 00173 } 00174 00175 void ASTTypeWriter::VisitVectorType(const VectorType *T) { 00176 Writer.AddTypeRef(T->getElementType(), Record); 00177 Record.push_back(T->getNumElements()); 00178 Record.push_back(T->getVectorKind()); 00179 Code = TYPE_VECTOR; 00180 } 00181 00182 void ASTTypeWriter::VisitExtVectorType(const ExtVectorType *T) { 00183 VisitVectorType(T); 00184 Code = TYPE_EXT_VECTOR; 00185 } 00186 00187 void ASTTypeWriter::VisitFunctionType(const FunctionType *T) { 00188 Writer.AddTypeRef(T->getReturnType(), Record); 00189 FunctionType::ExtInfo C = T->getExtInfo(); 00190 Record.push_back(C.getNoReturn()); 00191 Record.push_back(C.getHasRegParm()); 00192 Record.push_back(C.getRegParm()); 00193 // FIXME: need to stabilize encoding of calling convention... 00194 Record.push_back(C.getCC()); 00195 Record.push_back(C.getProducesResult()); 00196 00197 if (C.getHasRegParm() || C.getRegParm() || C.getProducesResult()) 00198 AbbrevToUse = 0; 00199 } 00200 00201 void ASTTypeWriter::VisitFunctionNoProtoType(const FunctionNoProtoType *T) { 00202 VisitFunctionType(T); 00203 Code = TYPE_FUNCTION_NO_PROTO; 00204 } 00205 00206 static void addExceptionSpec(ASTWriter &Writer, const FunctionProtoType *T, 00207 ASTWriter::RecordDataImpl &Record) { 00208 Record.push_back(T->getExceptionSpecType()); 00209 if (T->getExceptionSpecType() == EST_Dynamic) { 00210 Record.push_back(T->getNumExceptions()); 00211 for (unsigned I = 0, N = T->getNumExceptions(); I != N; ++I) 00212 Writer.AddTypeRef(T->getExceptionType(I), Record); 00213 } else if (T->getExceptionSpecType() == EST_ComputedNoexcept) { 00214 Writer.AddStmt(T->getNoexceptExpr()); 00215 } else if (T->getExceptionSpecType() == EST_Uninstantiated) { 00216 Writer.AddDeclRef(T->getExceptionSpecDecl(), Record); 00217 Writer.AddDeclRef(T->getExceptionSpecTemplate(), Record); 00218 } else if (T->getExceptionSpecType() == EST_Unevaluated) { 00219 Writer.AddDeclRef(T->getExceptionSpecDecl(), Record); 00220 } 00221 } 00222 00223 void ASTTypeWriter::VisitFunctionProtoType(const FunctionProtoType *T) { 00224 VisitFunctionType(T); 00225 00226 Record.push_back(T->isVariadic()); 00227 Record.push_back(T->hasTrailingReturn()); 00228 Record.push_back(T->getTypeQuals()); 00229 Record.push_back(static_cast<unsigned>(T->getRefQualifier())); 00230 addExceptionSpec(Writer, T, Record); 00231 00232 Record.push_back(T->getNumParams()); 00233 for (unsigned I = 0, N = T->getNumParams(); I != N; ++I) 00234 Writer.AddTypeRef(T->getParamType(I), Record); 00235 00236 if (T->isVariadic() || T->hasTrailingReturn() || T->getTypeQuals() || 00237 T->getRefQualifier() || T->getExceptionSpecType() != EST_None) 00238 AbbrevToUse = 0; 00239 00240 Code = TYPE_FUNCTION_PROTO; 00241 } 00242 00243 void ASTTypeWriter::VisitUnresolvedUsingType(const UnresolvedUsingType *T) { 00244 Writer.AddDeclRef(T->getDecl(), Record); 00245 Code = TYPE_UNRESOLVED_USING; 00246 } 00247 00248 void ASTTypeWriter::VisitTypedefType(const TypedefType *T) { 00249 Writer.AddDeclRef(T->getDecl(), Record); 00250 assert(!T->isCanonicalUnqualified() && "Invalid typedef ?"); 00251 Writer.AddTypeRef(T->getCanonicalTypeInternal(), Record); 00252 Code = TYPE_TYPEDEF; 00253 } 00254 00255 void ASTTypeWriter::VisitTypeOfExprType(const TypeOfExprType *T) { 00256 Writer.AddStmt(T->getUnderlyingExpr()); 00257 Code = TYPE_TYPEOF_EXPR; 00258 } 00259 00260 void ASTTypeWriter::VisitTypeOfType(const TypeOfType *T) { 00261 Writer.AddTypeRef(T->getUnderlyingType(), Record); 00262 Code = TYPE_TYPEOF; 00263 } 00264 00265 void ASTTypeWriter::VisitDecltypeType(const DecltypeType *T) { 00266 Writer.AddTypeRef(T->getUnderlyingType(), Record); 00267 Writer.AddStmt(T->getUnderlyingExpr()); 00268 Code = TYPE_DECLTYPE; 00269 } 00270 00271 void ASTTypeWriter::VisitUnaryTransformType(const UnaryTransformType *T) { 00272 Writer.AddTypeRef(T->getBaseType(), Record); 00273 Writer.AddTypeRef(T->getUnderlyingType(), Record); 00274 Record.push_back(T->getUTTKind()); 00275 Code = TYPE_UNARY_TRANSFORM; 00276 } 00277 00278 void ASTTypeWriter::VisitAutoType(const AutoType *T) { 00279 Writer.AddTypeRef(T->getDeducedType(), Record); 00280 Record.push_back(T->isDecltypeAuto()); 00281 if (T->getDeducedType().isNull()) 00282 Record.push_back(T->isDependentType()); 00283 Code = TYPE_AUTO; 00284 } 00285 00286 void ASTTypeWriter::VisitTagType(const TagType *T) { 00287 Record.push_back(T->isDependentType()); 00288 Writer.AddDeclRef(T->getDecl()->getCanonicalDecl(), Record); 00289 assert(!T->isBeingDefined() && 00290 "Cannot serialize in the middle of a type definition"); 00291 } 00292 00293 void ASTTypeWriter::VisitRecordType(const RecordType *T) { 00294 VisitTagType(T); 00295 Code = TYPE_RECORD; 00296 } 00297 00298 void ASTTypeWriter::VisitEnumType(const EnumType *T) { 00299 VisitTagType(T); 00300 Code = TYPE_ENUM; 00301 } 00302 00303 void ASTTypeWriter::VisitAttributedType(const AttributedType *T) { 00304 Writer.AddTypeRef(T->getModifiedType(), Record); 00305 Writer.AddTypeRef(T->getEquivalentType(), Record); 00306 Record.push_back(T->getAttrKind()); 00307 Code = TYPE_ATTRIBUTED; 00308 } 00309 00310 void 00311 ASTTypeWriter::VisitSubstTemplateTypeParmType( 00312 const SubstTemplateTypeParmType *T) { 00313 Writer.AddTypeRef(QualType(T->getReplacedParameter(), 0), Record); 00314 Writer.AddTypeRef(T->getReplacementType(), Record); 00315 Code = TYPE_SUBST_TEMPLATE_TYPE_PARM; 00316 } 00317 00318 void 00319 ASTTypeWriter::VisitSubstTemplateTypeParmPackType( 00320 const SubstTemplateTypeParmPackType *T) { 00321 Writer.AddTypeRef(QualType(T->getReplacedParameter(), 0), Record); 00322 Writer.AddTemplateArgument(T->getArgumentPack(), Record); 00323 Code = TYPE_SUBST_TEMPLATE_TYPE_PARM_PACK; 00324 } 00325 00326 void 00327 ASTTypeWriter::VisitTemplateSpecializationType( 00328 const TemplateSpecializationType *T) { 00329 Record.push_back(T->isDependentType()); 00330 Writer.AddTemplateName(T->getTemplateName(), Record); 00331 Record.push_back(T->getNumArgs()); 00332 for (TemplateSpecializationType::iterator ArgI = T->begin(), ArgE = T->end(); 00333 ArgI != ArgE; ++ArgI) 00334 Writer.AddTemplateArgument(*ArgI, Record); 00335 Writer.AddTypeRef(T->isTypeAlias() ? T->getAliasedType() : 00336 T->isCanonicalUnqualified() ? QualType() 00337 : T->getCanonicalTypeInternal(), 00338 Record); 00339 Code = TYPE_TEMPLATE_SPECIALIZATION; 00340 } 00341 00342 void 00343 ASTTypeWriter::VisitDependentSizedArrayType(const DependentSizedArrayType *T) { 00344 VisitArrayType(T); 00345 Writer.AddStmt(T->getSizeExpr()); 00346 Writer.AddSourceRange(T->getBracketsRange(), Record); 00347 Code = TYPE_DEPENDENT_SIZED_ARRAY; 00348 } 00349 00350 void 00351 ASTTypeWriter::VisitDependentSizedExtVectorType( 00352 const DependentSizedExtVectorType *T) { 00353 // FIXME: Serialize this type (C++ only) 00354 llvm_unreachable("Cannot serialize dependent sized extended vector types"); 00355 } 00356 00357 void 00358 ASTTypeWriter::VisitTemplateTypeParmType(const TemplateTypeParmType *T) { 00359 Record.push_back(T->getDepth()); 00360 Record.push_back(T->getIndex()); 00361 Record.push_back(T->isParameterPack()); 00362 Writer.AddDeclRef(T->getDecl(), Record); 00363 Code = TYPE_TEMPLATE_TYPE_PARM; 00364 } 00365 00366 void 00367 ASTTypeWriter::VisitDependentNameType(const DependentNameType *T) { 00368 Record.push_back(T->getKeyword()); 00369 Writer.AddNestedNameSpecifier(T->getQualifier(), Record); 00370 Writer.AddIdentifierRef(T->getIdentifier(), Record); 00371 Writer.AddTypeRef(T->isCanonicalUnqualified() ? QualType() 00372 : T->getCanonicalTypeInternal(), 00373 Record); 00374 Code = TYPE_DEPENDENT_NAME; 00375 } 00376 00377 void 00378 ASTTypeWriter::VisitDependentTemplateSpecializationType( 00379 const DependentTemplateSpecializationType *T) { 00380 Record.push_back(T->getKeyword()); 00381 Writer.AddNestedNameSpecifier(T->getQualifier(), Record); 00382 Writer.AddIdentifierRef(T->getIdentifier(), Record); 00383 Record.push_back(T->getNumArgs()); 00384 for (DependentTemplateSpecializationType::iterator 00385 I = T->begin(), E = T->end(); I != E; ++I) 00386 Writer.AddTemplateArgument(*I, Record); 00387 Code = TYPE_DEPENDENT_TEMPLATE_SPECIALIZATION; 00388 } 00389 00390 void ASTTypeWriter::VisitPackExpansionType(const PackExpansionType *T) { 00391 Writer.AddTypeRef(T->getPattern(), Record); 00392 if (Optional<unsigned> NumExpansions = T->getNumExpansions()) 00393 Record.push_back(*NumExpansions + 1); 00394 else 00395 Record.push_back(0); 00396 Code = TYPE_PACK_EXPANSION; 00397 } 00398 00399 void ASTTypeWriter::VisitParenType(const ParenType *T) { 00400 Writer.AddTypeRef(T->getInnerType(), Record); 00401 Code = TYPE_PAREN; 00402 } 00403 00404 void ASTTypeWriter::VisitElaboratedType(const ElaboratedType *T) { 00405 Record.push_back(T->getKeyword()); 00406 Writer.AddNestedNameSpecifier(T->getQualifier(), Record); 00407 Writer.AddTypeRef(T->getNamedType(), Record); 00408 Code = TYPE_ELABORATED; 00409 } 00410 00411 void ASTTypeWriter::VisitInjectedClassNameType(const InjectedClassNameType *T) { 00412 Writer.AddDeclRef(T->getDecl()->getCanonicalDecl(), Record); 00413 Writer.AddTypeRef(T->getInjectedSpecializationType(), Record); 00414 Code = TYPE_INJECTED_CLASS_NAME; 00415 } 00416 00417 void ASTTypeWriter::VisitObjCInterfaceType(const ObjCInterfaceType *T) { 00418 Writer.AddDeclRef(T->getDecl()->getCanonicalDecl(), Record); 00419 Code = TYPE_OBJC_INTERFACE; 00420 } 00421 00422 void ASTTypeWriter::VisitObjCObjectType(const ObjCObjectType *T) { 00423 Writer.AddTypeRef(T->getBaseType(), Record); 00424 Record.push_back(T->getNumProtocols()); 00425 for (const auto *I : T->quals()) 00426 Writer.AddDeclRef(I, Record); 00427 Code = TYPE_OBJC_OBJECT; 00428 } 00429 00430 void 00431 ASTTypeWriter::VisitObjCObjectPointerType(const ObjCObjectPointerType *T) { 00432 Writer.AddTypeRef(T->getPointeeType(), Record); 00433 Code = TYPE_OBJC_OBJECT_POINTER; 00434 } 00435 00436 void 00437 ASTTypeWriter::VisitAtomicType(const AtomicType *T) { 00438 Writer.AddTypeRef(T->getValueType(), Record); 00439 Code = TYPE_ATOMIC; 00440 } 00441 00442 namespace { 00443 00444 class TypeLocWriter : public TypeLocVisitor<TypeLocWriter> { 00445 ASTWriter &Writer; 00446 ASTWriter::RecordDataImpl &Record; 00447 00448 public: 00449 TypeLocWriter(ASTWriter &Writer, ASTWriter::RecordDataImpl &Record) 00450 : Writer(Writer), Record(Record) { } 00451 00452 #define ABSTRACT_TYPELOC(CLASS, PARENT) 00453 #define TYPELOC(CLASS, PARENT) \ 00454 void Visit##CLASS##TypeLoc(CLASS##TypeLoc TyLoc); 00455 #include "clang/AST/TypeLocNodes.def" 00456 00457 void VisitArrayTypeLoc(ArrayTypeLoc TyLoc); 00458 void VisitFunctionTypeLoc(FunctionTypeLoc TyLoc); 00459 }; 00460 00461 } 00462 00463 void TypeLocWriter::VisitQualifiedTypeLoc(QualifiedTypeLoc TL) { 00464 // nothing to do 00465 } 00466 void TypeLocWriter::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) { 00467 Writer.AddSourceLocation(TL.getBuiltinLoc(), Record); 00468 if (TL.needsExtraLocalData()) { 00469 Record.push_back(TL.getWrittenTypeSpec()); 00470 Record.push_back(TL.getWrittenSignSpec()); 00471 Record.push_back(TL.getWrittenWidthSpec()); 00472 Record.push_back(TL.hasModeAttr()); 00473 } 00474 } 00475 void TypeLocWriter::VisitComplexTypeLoc(ComplexTypeLoc TL) { 00476 Writer.AddSourceLocation(TL.getNameLoc(), Record); 00477 } 00478 void TypeLocWriter::VisitPointerTypeLoc(PointerTypeLoc TL) { 00479 Writer.AddSourceLocation(TL.getStarLoc(), Record); 00480 } 00481 void TypeLocWriter::VisitDecayedTypeLoc(DecayedTypeLoc TL) { 00482 // nothing to do 00483 } 00484 void TypeLocWriter::VisitAdjustedTypeLoc(AdjustedTypeLoc TL) { 00485 // nothing to do 00486 } 00487 void TypeLocWriter::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) { 00488 Writer.AddSourceLocation(TL.getCaretLoc(), Record); 00489 } 00490 void TypeLocWriter::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) { 00491 Writer.AddSourceLocation(TL.getAmpLoc(), Record); 00492 } 00493 void TypeLocWriter::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) { 00494 Writer.AddSourceLocation(TL.getAmpAmpLoc(), Record); 00495 } 00496 void TypeLocWriter::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) { 00497 Writer.AddSourceLocation(TL.getStarLoc(), Record); 00498 Writer.AddTypeSourceInfo(TL.getClassTInfo(), Record); 00499 } 00500 void TypeLocWriter::VisitArrayTypeLoc(ArrayTypeLoc TL) { 00501 Writer.AddSourceLocation(TL.getLBracketLoc(), Record); 00502 Writer.AddSourceLocation(TL.getRBracketLoc(), Record); 00503 Record.push_back(TL.getSizeExpr() ? 1 : 0); 00504 if (TL.getSizeExpr()) 00505 Writer.AddStmt(TL.getSizeExpr()); 00506 } 00507 void TypeLocWriter::VisitConstantArrayTypeLoc(ConstantArrayTypeLoc TL) { 00508 VisitArrayTypeLoc(TL); 00509 } 00510 void TypeLocWriter::VisitIncompleteArrayTypeLoc(IncompleteArrayTypeLoc TL) { 00511 VisitArrayTypeLoc(TL); 00512 } 00513 void TypeLocWriter::VisitVariableArrayTypeLoc(VariableArrayTypeLoc TL) { 00514 VisitArrayTypeLoc(TL); 00515 } 00516 void TypeLocWriter::VisitDependentSizedArrayTypeLoc( 00517 DependentSizedArrayTypeLoc TL) { 00518 VisitArrayTypeLoc(TL); 00519 } 00520 void TypeLocWriter::VisitDependentSizedExtVectorTypeLoc( 00521 DependentSizedExtVectorTypeLoc TL) { 00522 Writer.AddSourceLocation(TL.getNameLoc(), Record); 00523 } 00524 void TypeLocWriter::VisitVectorTypeLoc(VectorTypeLoc TL) { 00525 Writer.AddSourceLocation(TL.getNameLoc(), Record); 00526 } 00527 void TypeLocWriter::VisitExtVectorTypeLoc(ExtVectorTypeLoc TL) { 00528 Writer.AddSourceLocation(TL.getNameLoc(), Record); 00529 } 00530 void TypeLocWriter::VisitFunctionTypeLoc(FunctionTypeLoc TL) { 00531 Writer.AddSourceLocation(TL.getLocalRangeBegin(), Record); 00532 Writer.AddSourceLocation(TL.getLParenLoc(), Record); 00533 Writer.AddSourceLocation(TL.getRParenLoc(), Record); 00534 Writer.AddSourceLocation(TL.getLocalRangeEnd(), Record); 00535 for (unsigned i = 0, e = TL.getNumParams(); i != e; ++i) 00536 Writer.AddDeclRef(TL.getParam(i), Record); 00537 } 00538 void TypeLocWriter::VisitFunctionProtoTypeLoc(FunctionProtoTypeLoc TL) { 00539 VisitFunctionTypeLoc(TL); 00540 } 00541 void TypeLocWriter::VisitFunctionNoProtoTypeLoc(FunctionNoProtoTypeLoc TL) { 00542 VisitFunctionTypeLoc(TL); 00543 } 00544 void TypeLocWriter::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) { 00545 Writer.AddSourceLocation(TL.getNameLoc(), Record); 00546 } 00547 void TypeLocWriter::VisitTypedefTypeLoc(TypedefTypeLoc TL) { 00548 Writer.AddSourceLocation(TL.getNameLoc(), Record); 00549 } 00550 void TypeLocWriter::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) { 00551 Writer.AddSourceLocation(TL.getTypeofLoc(), Record); 00552 Writer.AddSourceLocation(TL.getLParenLoc(), Record); 00553 Writer.AddSourceLocation(TL.getRParenLoc(), Record); 00554 } 00555 void TypeLocWriter::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) { 00556 Writer.AddSourceLocation(TL.getTypeofLoc(), Record); 00557 Writer.AddSourceLocation(TL.getLParenLoc(), Record); 00558 Writer.AddSourceLocation(TL.getRParenLoc(), Record); 00559 Writer.AddTypeSourceInfo(TL.getUnderlyingTInfo(), Record); 00560 } 00561 void TypeLocWriter::VisitDecltypeTypeLoc(DecltypeTypeLoc TL) { 00562 Writer.AddSourceLocation(TL.getNameLoc(), Record); 00563 } 00564 void TypeLocWriter::VisitUnaryTransformTypeLoc(UnaryTransformTypeLoc TL) { 00565 Writer.AddSourceLocation(TL.getKWLoc(), Record); 00566 Writer.AddSourceLocation(TL.getLParenLoc(), Record); 00567 Writer.AddSourceLocation(TL.getRParenLoc(), Record); 00568 Writer.AddTypeSourceInfo(TL.getUnderlyingTInfo(), Record); 00569 } 00570 void TypeLocWriter::VisitAutoTypeLoc(AutoTypeLoc TL) { 00571 Writer.AddSourceLocation(TL.getNameLoc(), Record); 00572 } 00573 void TypeLocWriter::VisitRecordTypeLoc(RecordTypeLoc TL) { 00574 Writer.AddSourceLocation(TL.getNameLoc(), Record); 00575 } 00576 void TypeLocWriter::VisitEnumTypeLoc(EnumTypeLoc TL) { 00577 Writer.AddSourceLocation(TL.getNameLoc(), Record); 00578 } 00579 void TypeLocWriter::VisitAttributedTypeLoc(AttributedTypeLoc TL) { 00580 Writer.AddSourceLocation(TL.getAttrNameLoc(), Record); 00581 if (TL.hasAttrOperand()) { 00582 SourceRange range = TL.getAttrOperandParensRange(); 00583 Writer.AddSourceLocation(range.getBegin(), Record); 00584 Writer.AddSourceLocation(range.getEnd(), Record); 00585 } 00586 if (TL.hasAttrExprOperand()) { 00587 Expr *operand = TL.getAttrExprOperand(); 00588 Record.push_back(operand ? 1 : 0); 00589 if (operand) Writer.AddStmt(operand); 00590 } else if (TL.hasAttrEnumOperand()) { 00591 Writer.AddSourceLocation(TL.getAttrEnumOperandLoc(), Record); 00592 } 00593 } 00594 void TypeLocWriter::VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) { 00595 Writer.AddSourceLocation(TL.getNameLoc(), Record); 00596 } 00597 void TypeLocWriter::VisitSubstTemplateTypeParmTypeLoc( 00598 SubstTemplateTypeParmTypeLoc TL) { 00599 Writer.AddSourceLocation(TL.getNameLoc(), Record); 00600 } 00601 void TypeLocWriter::VisitSubstTemplateTypeParmPackTypeLoc( 00602 SubstTemplateTypeParmPackTypeLoc TL) { 00603 Writer.AddSourceLocation(TL.getNameLoc(), Record); 00604 } 00605 void TypeLocWriter::VisitTemplateSpecializationTypeLoc( 00606 TemplateSpecializationTypeLoc TL) { 00607 Writer.AddSourceLocation(TL.getTemplateKeywordLoc(), Record); 00608 Writer.AddSourceLocation(TL.getTemplateNameLoc(), Record); 00609 Writer.AddSourceLocation(TL.getLAngleLoc(), Record); 00610 Writer.AddSourceLocation(TL.getRAngleLoc(), Record); 00611 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i) 00612 Writer.AddTemplateArgumentLocInfo(TL.getArgLoc(i).getArgument().getKind(), 00613 TL.getArgLoc(i).getLocInfo(), Record); 00614 } 00615 void TypeLocWriter::VisitParenTypeLoc(ParenTypeLoc TL) { 00616 Writer.AddSourceLocation(TL.getLParenLoc(), Record); 00617 Writer.AddSourceLocation(TL.getRParenLoc(), Record); 00618 } 00619 void TypeLocWriter::VisitElaboratedTypeLoc(ElaboratedTypeLoc TL) { 00620 Writer.AddSourceLocation(TL.getElaboratedKeywordLoc(), Record); 00621 Writer.AddNestedNameSpecifierLoc(TL.getQualifierLoc(), Record); 00622 } 00623 void TypeLocWriter::VisitInjectedClassNameTypeLoc(InjectedClassNameTypeLoc TL) { 00624 Writer.AddSourceLocation(TL.getNameLoc(), Record); 00625 } 00626 void TypeLocWriter::VisitDependentNameTypeLoc(DependentNameTypeLoc TL) { 00627 Writer.AddSourceLocation(TL.getElaboratedKeywordLoc(), Record); 00628 Writer.AddNestedNameSpecifierLoc(TL.getQualifierLoc(), Record); 00629 Writer.AddSourceLocation(TL.getNameLoc(), Record); 00630 } 00631 void TypeLocWriter::VisitDependentTemplateSpecializationTypeLoc( 00632 DependentTemplateSpecializationTypeLoc TL) { 00633 Writer.AddSourceLocation(TL.getElaboratedKeywordLoc(), Record); 00634 Writer.AddNestedNameSpecifierLoc(TL.getQualifierLoc(), Record); 00635 Writer.AddSourceLocation(TL.getTemplateKeywordLoc(), Record); 00636 Writer.AddSourceLocation(TL.getTemplateNameLoc(), Record); 00637 Writer.AddSourceLocation(TL.getLAngleLoc(), Record); 00638 Writer.AddSourceLocation(TL.getRAngleLoc(), Record); 00639 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) 00640 Writer.AddTemplateArgumentLocInfo(TL.getArgLoc(I).getArgument().getKind(), 00641 TL.getArgLoc(I).getLocInfo(), Record); 00642 } 00643 void TypeLocWriter::VisitPackExpansionTypeLoc(PackExpansionTypeLoc TL) { 00644 Writer.AddSourceLocation(TL.getEllipsisLoc(), Record); 00645 } 00646 void TypeLocWriter::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) { 00647 Writer.AddSourceLocation(TL.getNameLoc(), Record); 00648 } 00649 void TypeLocWriter::VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) { 00650 Record.push_back(TL.hasBaseTypeAsWritten()); 00651 Writer.AddSourceLocation(TL.getLAngleLoc(), Record); 00652 Writer.AddSourceLocation(TL.getRAngleLoc(), Record); 00653 for (unsigned i = 0, e = TL.getNumProtocols(); i != e; ++i) 00654 Writer.AddSourceLocation(TL.getProtocolLoc(i), Record); 00655 } 00656 void TypeLocWriter::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) { 00657 Writer.AddSourceLocation(TL.getStarLoc(), Record); 00658 } 00659 void TypeLocWriter::VisitAtomicTypeLoc(AtomicTypeLoc TL) { 00660 Writer.AddSourceLocation(TL.getKWLoc(), Record); 00661 Writer.AddSourceLocation(TL.getLParenLoc(), Record); 00662 Writer.AddSourceLocation(TL.getRParenLoc(), Record); 00663 } 00664 00665 void ASTWriter::WriteTypeAbbrevs() { 00666 using namespace llvm; 00667 00668 BitCodeAbbrev *Abv; 00669 00670 // Abbreviation for TYPE_EXT_QUAL 00671 Abv = new BitCodeAbbrev(); 00672 Abv->Add(BitCodeAbbrevOp(serialization::TYPE_EXT_QUAL)); 00673 Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Type 00674 Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 3)); // Quals 00675 TypeExtQualAbbrev = Stream.EmitAbbrev(Abv); 00676 00677 // Abbreviation for TYPE_FUNCTION_PROTO 00678 Abv = new BitCodeAbbrev(); 00679 Abv->Add(BitCodeAbbrevOp(serialization::TYPE_FUNCTION_PROTO)); 00680 // FunctionType 00681 Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // ReturnType 00682 Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // NoReturn 00683 Abv->Add(BitCodeAbbrevOp(0)); // HasRegParm 00684 Abv->Add(BitCodeAbbrevOp(0)); // RegParm 00685 Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // CC 00686 Abv->Add(BitCodeAbbrevOp(0)); // ProducesResult 00687 // FunctionProtoType 00688 Abv->Add(BitCodeAbbrevOp(0)); // IsVariadic 00689 Abv->Add(BitCodeAbbrevOp(0)); // HasTrailingReturn 00690 Abv->Add(BitCodeAbbrevOp(0)); // TypeQuals 00691 Abv->Add(BitCodeAbbrevOp(0)); // RefQualifier 00692 Abv->Add(BitCodeAbbrevOp(EST_None)); // ExceptionSpec 00693 Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // NumParams 00694 Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array)); 00695 Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Params 00696 TypeFunctionProtoAbbrev = Stream.EmitAbbrev(Abv); 00697 } 00698 00699 //===----------------------------------------------------------------------===// 00700 // ASTWriter Implementation 00701 //===----------------------------------------------------------------------===// 00702 00703 static void EmitBlockID(unsigned ID, const char *Name, 00704 llvm::BitstreamWriter &Stream, 00705 ASTWriter::RecordDataImpl &Record) { 00706 Record.clear(); 00707 Record.push_back(ID); 00708 Stream.EmitRecord(llvm::bitc::BLOCKINFO_CODE_SETBID, Record); 00709 00710 // Emit the block name if present. 00711 if (!Name || Name[0] == 0) 00712 return; 00713 Record.clear(); 00714 while (*Name) 00715 Record.push_back(*Name++); 00716 Stream.EmitRecord(llvm::bitc::BLOCKINFO_CODE_BLOCKNAME, Record); 00717 } 00718 00719 static void EmitRecordID(unsigned ID, const char *Name, 00720 llvm::BitstreamWriter &Stream, 00721 ASTWriter::RecordDataImpl &Record) { 00722 Record.clear(); 00723 Record.push_back(ID); 00724 while (*Name) 00725 Record.push_back(*Name++); 00726 Stream.EmitRecord(llvm::bitc::BLOCKINFO_CODE_SETRECORDNAME, Record); 00727 } 00728 00729 static void AddStmtsExprs(llvm::BitstreamWriter &Stream, 00730 ASTWriter::RecordDataImpl &Record) { 00731 #define RECORD(X) EmitRecordID(X, #X, Stream, Record) 00732 RECORD(STMT_STOP); 00733 RECORD(STMT_NULL_PTR); 00734 RECORD(STMT_REF_PTR); 00735 RECORD(STMT_NULL); 00736 RECORD(STMT_COMPOUND); 00737 RECORD(STMT_CASE); 00738 RECORD(STMT_DEFAULT); 00739 RECORD(STMT_LABEL); 00740 RECORD(STMT_ATTRIBUTED); 00741 RECORD(STMT_IF); 00742 RECORD(STMT_SWITCH); 00743 RECORD(STMT_WHILE); 00744 RECORD(STMT_DO); 00745 RECORD(STMT_FOR); 00746 RECORD(STMT_GOTO); 00747 RECORD(STMT_INDIRECT_GOTO); 00748 RECORD(STMT_CONTINUE); 00749 RECORD(STMT_BREAK); 00750 RECORD(STMT_RETURN); 00751 RECORD(STMT_DECL); 00752 RECORD(STMT_GCCASM); 00753 RECORD(STMT_MSASM); 00754 RECORD(EXPR_PREDEFINED); 00755 RECORD(EXPR_DECL_REF); 00756 RECORD(EXPR_INTEGER_LITERAL); 00757 RECORD(EXPR_FLOATING_LITERAL); 00758 RECORD(EXPR_IMAGINARY_LITERAL); 00759 RECORD(EXPR_STRING_LITERAL); 00760 RECORD(EXPR_CHARACTER_LITERAL); 00761 RECORD(EXPR_PAREN); 00762 RECORD(EXPR_PAREN_LIST); 00763 RECORD(EXPR_UNARY_OPERATOR); 00764 RECORD(EXPR_SIZEOF_ALIGN_OF); 00765 RECORD(EXPR_ARRAY_SUBSCRIPT); 00766 RECORD(EXPR_CALL); 00767 RECORD(EXPR_MEMBER); 00768 RECORD(EXPR_BINARY_OPERATOR); 00769 RECORD(EXPR_COMPOUND_ASSIGN_OPERATOR); 00770 RECORD(EXPR_CONDITIONAL_OPERATOR); 00771 RECORD(EXPR_IMPLICIT_CAST); 00772 RECORD(EXPR_CSTYLE_CAST); 00773 RECORD(EXPR_COMPOUND_LITERAL); 00774 RECORD(EXPR_EXT_VECTOR_ELEMENT); 00775 RECORD(EXPR_INIT_LIST); 00776 RECORD(EXPR_DESIGNATED_INIT); 00777 RECORD(EXPR_IMPLICIT_VALUE_INIT); 00778 RECORD(EXPR_VA_ARG); 00779 RECORD(EXPR_ADDR_LABEL); 00780 RECORD(EXPR_STMT); 00781 RECORD(EXPR_CHOOSE); 00782 RECORD(EXPR_GNU_NULL); 00783 RECORD(EXPR_SHUFFLE_VECTOR); 00784 RECORD(EXPR_BLOCK); 00785 RECORD(EXPR_GENERIC_SELECTION); 00786 RECORD(EXPR_OBJC_STRING_LITERAL); 00787 RECORD(EXPR_OBJC_BOXED_EXPRESSION); 00788 RECORD(EXPR_OBJC_ARRAY_LITERAL); 00789 RECORD(EXPR_OBJC_DICTIONARY_LITERAL); 00790 RECORD(EXPR_OBJC_ENCODE); 00791 RECORD(EXPR_OBJC_SELECTOR_EXPR); 00792 RECORD(EXPR_OBJC_PROTOCOL_EXPR); 00793 RECORD(EXPR_OBJC_IVAR_REF_EXPR); 00794 RECORD(EXPR_OBJC_PROPERTY_REF_EXPR); 00795 RECORD(EXPR_OBJC_KVC_REF_EXPR); 00796 RECORD(EXPR_OBJC_MESSAGE_EXPR); 00797 RECORD(STMT_OBJC_FOR_COLLECTION); 00798 RECORD(STMT_OBJC_CATCH); 00799 RECORD(STMT_OBJC_FINALLY); 00800 RECORD(STMT_OBJC_AT_TRY); 00801 RECORD(STMT_OBJC_AT_SYNCHRONIZED); 00802 RECORD(STMT_OBJC_AT_THROW); 00803 RECORD(EXPR_OBJC_BOOL_LITERAL); 00804 RECORD(STMT_CXX_CATCH); 00805 RECORD(STMT_CXX_TRY); 00806 RECORD(STMT_CXX_FOR_RANGE); 00807 RECORD(EXPR_CXX_OPERATOR_CALL); 00808 RECORD(EXPR_CXX_MEMBER_CALL); 00809 RECORD(EXPR_CXX_CONSTRUCT); 00810 RECORD(EXPR_CXX_TEMPORARY_OBJECT); 00811 RECORD(EXPR_CXX_STATIC_CAST); 00812 RECORD(EXPR_CXX_DYNAMIC_CAST); 00813 RECORD(EXPR_CXX_REINTERPRET_CAST); 00814 RECORD(EXPR_CXX_CONST_CAST); 00815 RECORD(EXPR_CXX_FUNCTIONAL_CAST); 00816 RECORD(EXPR_USER_DEFINED_LITERAL); 00817 RECORD(EXPR_CXX_STD_INITIALIZER_LIST); 00818 RECORD(EXPR_CXX_BOOL_LITERAL); 00819 RECORD(EXPR_CXX_NULL_PTR_LITERAL); 00820 RECORD(EXPR_CXX_TYPEID_EXPR); 00821 RECORD(EXPR_CXX_TYPEID_TYPE); 00822 RECORD(EXPR_CXX_THIS); 00823 RECORD(EXPR_CXX_THROW); 00824 RECORD(EXPR_CXX_DEFAULT_ARG); 00825 RECORD(EXPR_CXX_DEFAULT_INIT); 00826 RECORD(EXPR_CXX_BIND_TEMPORARY); 00827 RECORD(EXPR_CXX_SCALAR_VALUE_INIT); 00828 RECORD(EXPR_CXX_NEW); 00829 RECORD(EXPR_CXX_DELETE); 00830 RECORD(EXPR_CXX_PSEUDO_DESTRUCTOR); 00831 RECORD(EXPR_EXPR_WITH_CLEANUPS); 00832 RECORD(EXPR_CXX_DEPENDENT_SCOPE_MEMBER); 00833 RECORD(EXPR_CXX_DEPENDENT_SCOPE_DECL_REF); 00834 RECORD(EXPR_CXX_UNRESOLVED_CONSTRUCT); 00835 RECORD(EXPR_CXX_UNRESOLVED_MEMBER); 00836 RECORD(EXPR_CXX_UNRESOLVED_LOOKUP); 00837 RECORD(EXPR_CXX_EXPRESSION_TRAIT); 00838 RECORD(EXPR_CXX_NOEXCEPT); 00839 RECORD(EXPR_OPAQUE_VALUE); 00840 RECORD(EXPR_BINARY_CONDITIONAL_OPERATOR); 00841 RECORD(EXPR_TYPE_TRAIT); 00842 RECORD(EXPR_ARRAY_TYPE_TRAIT); 00843 RECORD(EXPR_PACK_EXPANSION); 00844 RECORD(EXPR_SIZEOF_PACK); 00845 RECORD(EXPR_SUBST_NON_TYPE_TEMPLATE_PARM); 00846 RECORD(EXPR_SUBST_NON_TYPE_TEMPLATE_PARM_PACK); 00847 RECORD(EXPR_FUNCTION_PARM_PACK); 00848 RECORD(EXPR_MATERIALIZE_TEMPORARY); 00849 RECORD(EXPR_CUDA_KERNEL_CALL); 00850 RECORD(EXPR_CXX_UUIDOF_EXPR); 00851 RECORD(EXPR_CXX_UUIDOF_TYPE); 00852 RECORD(EXPR_LAMBDA); 00853 #undef RECORD 00854 } 00855 00856 void ASTWriter::WriteBlockInfoBlock() { 00857 RecordData Record; 00858 Stream.EnterSubblock(llvm::bitc::BLOCKINFO_BLOCK_ID, 3); 00859 00860 #define BLOCK(X) EmitBlockID(X ## _ID, #X, Stream, Record) 00861 #define RECORD(X) EmitRecordID(X, #X, Stream, Record) 00862 00863 // Control Block. 00864 BLOCK(CONTROL_BLOCK); 00865 RECORD(METADATA); 00866 RECORD(SIGNATURE); 00867 RECORD(MODULE_NAME); 00868 RECORD(MODULE_MAP_FILE); 00869 RECORD(IMPORTS); 00870 RECORD(LANGUAGE_OPTIONS); 00871 RECORD(TARGET_OPTIONS); 00872 RECORD(ORIGINAL_FILE); 00873 RECORD(ORIGINAL_PCH_DIR); 00874 RECORD(ORIGINAL_FILE_ID); 00875 RECORD(INPUT_FILE_OFFSETS); 00876 RECORD(DIAGNOSTIC_OPTIONS); 00877 RECORD(FILE_SYSTEM_OPTIONS); 00878 RECORD(HEADER_SEARCH_OPTIONS); 00879 RECORD(PREPROCESSOR_OPTIONS); 00880 00881 BLOCK(INPUT_FILES_BLOCK); 00882 RECORD(INPUT_FILE); 00883 00884 // AST Top-Level Block. 00885 BLOCK(AST_BLOCK); 00886 RECORD(TYPE_OFFSET); 00887 RECORD(DECL_OFFSET); 00888 RECORD(IDENTIFIER_OFFSET); 00889 RECORD(IDENTIFIER_TABLE); 00890 RECORD(EAGERLY_DESERIALIZED_DECLS); 00891 RECORD(SPECIAL_TYPES); 00892 RECORD(STATISTICS); 00893 RECORD(TENTATIVE_DEFINITIONS); 00894 RECORD(UNUSED_FILESCOPED_DECLS); 00895 RECORD(LOCALLY_SCOPED_EXTERN_C_DECLS); 00896 RECORD(SELECTOR_OFFSETS); 00897 RECORD(METHOD_POOL); 00898 RECORD(PP_COUNTER_VALUE); 00899 RECORD(SOURCE_LOCATION_OFFSETS); 00900 RECORD(SOURCE_LOCATION_PRELOADS); 00901 RECORD(EXT_VECTOR_DECLS); 00902 RECORD(PPD_ENTITIES_OFFSETS); 00903 RECORD(REFERENCED_SELECTOR_POOL); 00904 RECORD(TU_UPDATE_LEXICAL); 00905 RECORD(LOCAL_REDECLARATIONS_MAP); 00906 RECORD(SEMA_DECL_REFS); 00907 RECORD(WEAK_UNDECLARED_IDENTIFIERS); 00908 RECORD(PENDING_IMPLICIT_INSTANTIATIONS); 00909 RECORD(DECL_REPLACEMENTS); 00910 RECORD(UPDATE_VISIBLE); 00911 RECORD(DECL_UPDATE_OFFSETS); 00912 RECORD(DECL_UPDATES); 00913 RECORD(CXX_BASE_SPECIFIER_OFFSETS); 00914 RECORD(DIAG_PRAGMA_MAPPINGS); 00915 RECORD(CUDA_SPECIAL_DECL_REFS); 00916 RECORD(HEADER_SEARCH_TABLE); 00917 RECORD(FP_PRAGMA_OPTIONS); 00918 RECORD(OPENCL_EXTENSIONS); 00919 RECORD(DELEGATING_CTORS); 00920 RECORD(KNOWN_NAMESPACES); 00921 RECORD(UNDEFINED_BUT_USED); 00922 RECORD(MODULE_OFFSET_MAP); 00923 RECORD(SOURCE_MANAGER_LINE_TABLE); 00924 RECORD(OBJC_CATEGORIES_MAP); 00925 RECORD(FILE_SORTED_DECLS); 00926 RECORD(IMPORTED_MODULES); 00927 RECORD(MERGED_DECLARATIONS); 00928 RECORD(LOCAL_REDECLARATIONS); 00929 RECORD(OBJC_CATEGORIES); 00930 RECORD(MACRO_OFFSET); 00931 RECORD(MACRO_TABLE); 00932 RECORD(LATE_PARSED_TEMPLATE); 00933 RECORD(OPTIMIZE_PRAGMA_OPTIONS); 00934 00935 // SourceManager Block. 00936 BLOCK(SOURCE_MANAGER_BLOCK); 00937 RECORD(SM_SLOC_FILE_ENTRY); 00938 RECORD(SM_SLOC_BUFFER_ENTRY); 00939 RECORD(SM_SLOC_BUFFER_BLOB); 00940 RECORD(SM_SLOC_EXPANSION_ENTRY); 00941 00942 // Preprocessor Block. 00943 BLOCK(PREPROCESSOR_BLOCK); 00944 RECORD(PP_MACRO_OBJECT_LIKE); 00945 RECORD(PP_MACRO_FUNCTION_LIKE); 00946 RECORD(PP_TOKEN); 00947 00948 // Decls and Types block. 00949 BLOCK(DECLTYPES_BLOCK); 00950 RECORD(TYPE_EXT_QUAL); 00951 RECORD(TYPE_COMPLEX); 00952 RECORD(TYPE_POINTER); 00953 RECORD(TYPE_BLOCK_POINTER); 00954 RECORD(TYPE_LVALUE_REFERENCE); 00955 RECORD(TYPE_RVALUE_REFERENCE); 00956 RECORD(TYPE_MEMBER_POINTER); 00957 RECORD(TYPE_CONSTANT_ARRAY); 00958 RECORD(TYPE_INCOMPLETE_ARRAY); 00959 RECORD(TYPE_VARIABLE_ARRAY); 00960 RECORD(TYPE_VECTOR); 00961 RECORD(TYPE_EXT_VECTOR); 00962 RECORD(TYPE_FUNCTION_NO_PROTO); 00963 RECORD(TYPE_FUNCTION_PROTO); 00964 RECORD(TYPE_TYPEDEF); 00965 RECORD(TYPE_TYPEOF_EXPR); 00966 RECORD(TYPE_TYPEOF); 00967 RECORD(TYPE_RECORD); 00968 RECORD(TYPE_ENUM); 00969 RECORD(TYPE_OBJC_INTERFACE); 00970 RECORD(TYPE_OBJC_OBJECT_POINTER); 00971 RECORD(TYPE_DECLTYPE); 00972 RECORD(TYPE_ELABORATED); 00973 RECORD(TYPE_SUBST_TEMPLATE_TYPE_PARM); 00974 RECORD(TYPE_UNRESOLVED_USING); 00975 RECORD(TYPE_INJECTED_CLASS_NAME); 00976 RECORD(TYPE_OBJC_OBJECT); 00977 RECORD(TYPE_TEMPLATE_TYPE_PARM); 00978 RECORD(TYPE_TEMPLATE_SPECIALIZATION); 00979 RECORD(TYPE_DEPENDENT_NAME); 00980 RECORD(TYPE_DEPENDENT_TEMPLATE_SPECIALIZATION); 00981 RECORD(TYPE_DEPENDENT_SIZED_ARRAY); 00982 RECORD(TYPE_PAREN); 00983 RECORD(TYPE_PACK_EXPANSION); 00984 RECORD(TYPE_ATTRIBUTED); 00985 RECORD(TYPE_SUBST_TEMPLATE_TYPE_PARM_PACK); 00986 RECORD(TYPE_AUTO); 00987 RECORD(TYPE_UNARY_TRANSFORM); 00988 RECORD(TYPE_ATOMIC); 00989 RECORD(TYPE_DECAYED); 00990 RECORD(TYPE_ADJUSTED); 00991 RECORD(DECL_TYPEDEF); 00992 RECORD(DECL_TYPEALIAS); 00993 RECORD(DECL_ENUM); 00994 RECORD(DECL_RECORD); 00995 RECORD(DECL_ENUM_CONSTANT); 00996 RECORD(DECL_FUNCTION); 00997 RECORD(DECL_OBJC_METHOD); 00998 RECORD(DECL_OBJC_INTERFACE); 00999 RECORD(DECL_OBJC_PROTOCOL); 01000 RECORD(DECL_OBJC_IVAR); 01001 RECORD(DECL_OBJC_AT_DEFS_FIELD); 01002 RECORD(DECL_OBJC_CATEGORY); 01003 RECORD(DECL_OBJC_CATEGORY_IMPL); 01004 RECORD(DECL_OBJC_IMPLEMENTATION); 01005 RECORD(DECL_OBJC_COMPATIBLE_ALIAS); 01006 RECORD(DECL_OBJC_PROPERTY); 01007 RECORD(DECL_OBJC_PROPERTY_IMPL); 01008 RECORD(DECL_FIELD); 01009 RECORD(DECL_MS_PROPERTY); 01010 RECORD(DECL_VAR); 01011 RECORD(DECL_IMPLICIT_PARAM); 01012 RECORD(DECL_PARM_VAR); 01013 RECORD(DECL_FILE_SCOPE_ASM); 01014 RECORD(DECL_BLOCK); 01015 RECORD(DECL_CONTEXT_LEXICAL); 01016 RECORD(DECL_CONTEXT_VISIBLE); 01017 RECORD(DECL_NAMESPACE); 01018 RECORD(DECL_NAMESPACE_ALIAS); 01019 RECORD(DECL_USING); 01020 RECORD(DECL_USING_SHADOW); 01021 RECORD(DECL_USING_DIRECTIVE); 01022 RECORD(DECL_UNRESOLVED_USING_VALUE); 01023 RECORD(DECL_UNRESOLVED_USING_TYPENAME); 01024 RECORD(DECL_LINKAGE_SPEC); 01025 RECORD(DECL_CXX_RECORD); 01026 RECORD(DECL_CXX_METHOD); 01027 RECORD(DECL_CXX_CONSTRUCTOR); 01028 RECORD(DECL_CXX_DESTRUCTOR); 01029 RECORD(DECL_CXX_CONVERSION); 01030 RECORD(DECL_ACCESS_SPEC); 01031 RECORD(DECL_FRIEND); 01032 RECORD(DECL_FRIEND_TEMPLATE); 01033 RECORD(DECL_CLASS_TEMPLATE); 01034 RECORD(DECL_CLASS_TEMPLATE_SPECIALIZATION); 01035 RECORD(DECL_CLASS_TEMPLATE_PARTIAL_SPECIALIZATION); 01036 RECORD(DECL_VAR_TEMPLATE); 01037 RECORD(DECL_VAR_TEMPLATE_SPECIALIZATION); 01038 RECORD(DECL_VAR_TEMPLATE_PARTIAL_SPECIALIZATION); 01039 RECORD(DECL_FUNCTION_TEMPLATE); 01040 RECORD(DECL_TEMPLATE_TYPE_PARM); 01041 RECORD(DECL_NON_TYPE_TEMPLATE_PARM); 01042 RECORD(DECL_TEMPLATE_TEMPLATE_PARM); 01043 RECORD(DECL_STATIC_ASSERT); 01044 RECORD(DECL_CXX_BASE_SPECIFIERS); 01045 RECORD(DECL_INDIRECTFIELD); 01046 RECORD(DECL_EXPANDED_NON_TYPE_TEMPLATE_PARM_PACK); 01047 01048 // Statements and Exprs can occur in the Decls and Types block. 01049 AddStmtsExprs(Stream, Record); 01050 01051 BLOCK(PREPROCESSOR_DETAIL_BLOCK); 01052 RECORD(PPD_MACRO_EXPANSION); 01053 RECORD(PPD_MACRO_DEFINITION); 01054 RECORD(PPD_INCLUSION_DIRECTIVE); 01055 01056 #undef RECORD 01057 #undef BLOCK 01058 Stream.ExitBlock(); 01059 } 01060 01061 /// \brief Adjusts the given filename to only write out the portion of the 01062 /// filename that is not part of the system root directory. 01063 /// 01064 /// \param Filename the file name to adjust. 01065 /// 01066 /// \param isysroot When non-NULL, the PCH file is a relocatable PCH file and 01067 /// the returned filename will be adjusted by this system root. 01068 /// 01069 /// \returns either the original filename (if it needs no adjustment) or the 01070 /// adjusted filename (which points into the @p Filename parameter). 01071 static const char * 01072 adjustFilenameForRelocatablePCH(const char *Filename, StringRef isysroot) { 01073 assert(Filename && "No file name to adjust?"); 01074 01075 if (isysroot.empty()) 01076 return Filename; 01077 01078 // Verify that the filename and the system root have the same prefix. 01079 unsigned Pos = 0; 01080 for (; Filename[Pos] && Pos < isysroot.size(); ++Pos) 01081 if (Filename[Pos] != isysroot[Pos]) 01082 return Filename; // Prefixes don't match. 01083 01084 // We hit the end of the filename before we hit the end of the system root. 01085 if (!Filename[Pos]) 01086 return Filename; 01087 01088 // If the file name has a '/' at the current position, skip over the '/'. 01089 // We distinguish sysroot-based includes from absolute includes by the 01090 // absence of '/' at the beginning of sysroot-based includes. 01091 if (Filename[Pos] == '/') 01092 ++Pos; 01093 01094 return Filename + Pos; 01095 } 01096 01097 static ASTFileSignature getSignature() { 01098 while (1) { 01099 if (ASTFileSignature S = llvm::sys::Process::GetRandomNumber()) 01100 return S; 01101 // Rely on GetRandomNumber to eventually return non-zero... 01102 } 01103 } 01104 01105 /// \brief Write the control block. 01106 void ASTWriter::WriteControlBlock(Preprocessor &PP, ASTContext &Context, 01107 StringRef isysroot, 01108 const std::string &OutputFile) { 01109 using namespace llvm; 01110 Stream.EnterSubblock(CONTROL_BLOCK_ID, 5); 01111 RecordData Record; 01112 01113 // Metadata 01114 BitCodeAbbrev *MetadataAbbrev = new BitCodeAbbrev(); 01115 MetadataAbbrev->Add(BitCodeAbbrevOp(METADATA)); 01116 MetadataAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 16)); // Major 01117 MetadataAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 16)); // Minor 01118 MetadataAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 16)); // Clang maj. 01119 MetadataAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 16)); // Clang min. 01120 MetadataAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Relocatable 01121 MetadataAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Errors 01122 MetadataAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // SVN branch/tag 01123 unsigned MetadataAbbrevCode = Stream.EmitAbbrev(MetadataAbbrev); 01124 Record.push_back(METADATA); 01125 Record.push_back(VERSION_MAJOR); 01126 Record.push_back(VERSION_MINOR); 01127 Record.push_back(CLANG_VERSION_MAJOR); 01128 Record.push_back(CLANG_VERSION_MINOR); 01129 Record.push_back(!isysroot.empty()); 01130 Record.push_back(ASTHasCompilerErrors); 01131 Stream.EmitRecordWithBlob(MetadataAbbrevCode, Record, 01132 getClangFullRepositoryVersion()); 01133 01134 // Signature 01135 Record.clear(); 01136 Record.push_back(getSignature()); 01137 Stream.EmitRecord(SIGNATURE, Record); 01138 01139 // Module name 01140 if (WritingModule) { 01141 BitCodeAbbrev *Abbrev = new BitCodeAbbrev(); 01142 Abbrev->Add(BitCodeAbbrevOp(MODULE_NAME)); 01143 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name 01144 unsigned AbbrevCode = Stream.EmitAbbrev(Abbrev); 01145 RecordData Record; 01146 Record.push_back(MODULE_NAME); 01147 Stream.EmitRecordWithBlob(AbbrevCode, Record, WritingModule->Name); 01148 } 01149 01150 // Module map file 01151 if (WritingModule) { 01152 Record.clear(); 01153 auto addModMap = [&](const FileEntry *F) { 01154 SmallString<128> ModuleMap(F->getName()); 01155 llvm::sys::fs::make_absolute(ModuleMap); 01156 AddString(ModuleMap.str(), Record); 01157 }; 01158 01159 auto &Map = PP.getHeaderSearchInfo().getModuleMap(); 01160 01161 // Primary module map file. 01162 addModMap(Map.getModuleMapFileForUniquing(WritingModule)); 01163 01164 // Additional module map files. 01165 if (auto *AdditionalModMaps = Map.getAdditionalModuleMapFiles(WritingModule)) { 01166 Record.push_back(AdditionalModMaps->size()); 01167 for (const FileEntry *F : *AdditionalModMaps) 01168 addModMap(F); 01169 } else { 01170 Record.push_back(0); 01171 } 01172 01173 Stream.EmitRecord(MODULE_MAP_FILE, Record); 01174 } 01175 01176 // Imports 01177 if (Chain) { 01178 serialization::ModuleManager &Mgr = Chain->getModuleManager(); 01179 Record.clear(); 01180 01181 for (ModuleManager::ModuleIterator M = Mgr.begin(), MEnd = Mgr.end(); 01182 M != MEnd; ++M) { 01183 // Skip modules that weren't directly imported. 01184 if (!(*M)->isDirectlyImported()) 01185 continue; 01186 01187 Record.push_back((unsigned)(*M)->Kind); // FIXME: Stable encoding 01188 AddSourceLocation((*M)->ImportLoc, Record); 01189 Record.push_back((*M)->File->getSize()); 01190 Record.push_back((*M)->File->getModificationTime()); 01191 Record.push_back((*M)->Signature); 01192 const std::string &FileName = (*M)->FileName; 01193 Record.push_back(FileName.size()); 01194 Record.append(FileName.begin(), FileName.end()); 01195 } 01196 Stream.EmitRecord(IMPORTS, Record); 01197 } 01198 01199 // Language options. 01200 Record.clear(); 01201 const LangOptions &LangOpts = Context.getLangOpts(); 01202 #define LANGOPT(Name, Bits, Default, Description) \ 01203 Record.push_back(LangOpts.Name); 01204 #define ENUM_LANGOPT(Name, Type, Bits, Default, Description) \ 01205 Record.push_back(static_cast<unsigned>(LangOpts.get##Name())); 01206 #include "clang/Basic/LangOptions.def" 01207 #define SANITIZER(NAME, ID) \ 01208 Record.push_back(LangOpts.Sanitize.has(SanitizerKind::ID)); 01209 #include "clang/Basic/Sanitizers.def" 01210 01211 Record.push_back((unsigned) LangOpts.ObjCRuntime.getKind()); 01212 AddVersionTuple(LangOpts.ObjCRuntime.getVersion(), Record); 01213 01214 Record.push_back(LangOpts.CurrentModule.size()); 01215 Record.append(LangOpts.CurrentModule.begin(), LangOpts.CurrentModule.end()); 01216 01217 // Comment options. 01218 Record.push_back(LangOpts.CommentOpts.BlockCommandNames.size()); 01219 for (CommentOptions::BlockCommandNamesTy::const_iterator 01220 I = LangOpts.CommentOpts.BlockCommandNames.begin(), 01221 IEnd = LangOpts.CommentOpts.BlockCommandNames.end(); 01222 I != IEnd; ++I) { 01223 AddString(*I, Record); 01224 } 01225 Record.push_back(LangOpts.CommentOpts.ParseAllComments); 01226 01227 Stream.EmitRecord(LANGUAGE_OPTIONS, Record); 01228 01229 // Target options. 01230 Record.clear(); 01231 const TargetInfo &Target = Context.getTargetInfo(); 01232 const TargetOptions &TargetOpts = Target.getTargetOpts(); 01233 AddString(TargetOpts.Triple, Record); 01234 AddString(TargetOpts.CPU, Record); 01235 AddString(TargetOpts.ABI, Record); 01236 Record.push_back(TargetOpts.FeaturesAsWritten.size()); 01237 for (unsigned I = 0, N = TargetOpts.FeaturesAsWritten.size(); I != N; ++I) { 01238 AddString(TargetOpts.FeaturesAsWritten[I], Record); 01239 } 01240 Record.push_back(TargetOpts.Features.size()); 01241 for (unsigned I = 0, N = TargetOpts.Features.size(); I != N; ++I) { 01242 AddString(TargetOpts.Features[I], Record); 01243 } 01244 Stream.EmitRecord(TARGET_OPTIONS, Record); 01245 01246 // Diagnostic options. 01247 Record.clear(); 01248 const DiagnosticOptions &DiagOpts 01249 = Context.getDiagnostics().getDiagnosticOptions(); 01250 #define DIAGOPT(Name, Bits, Default) Record.push_back(DiagOpts.Name); 01251 #define ENUM_DIAGOPT(Name, Type, Bits, Default) \ 01252 Record.push_back(static_cast<unsigned>(DiagOpts.get##Name())); 01253 #include "clang/Basic/DiagnosticOptions.def" 01254 Record.push_back(DiagOpts.Warnings.size()); 01255 for (unsigned I = 0, N = DiagOpts.Warnings.size(); I != N; ++I) 01256 AddString(DiagOpts.Warnings[I], Record); 01257 Record.push_back(DiagOpts.Remarks.size()); 01258 for (unsigned I = 0, N = DiagOpts.Remarks.size(); I != N; ++I) 01259 AddString(DiagOpts.Remarks[I], Record); 01260 // Note: we don't serialize the log or serialization file names, because they 01261 // are generally transient files and will almost always be overridden. 01262 Stream.EmitRecord(DIAGNOSTIC_OPTIONS, Record); 01263 01264 // File system options. 01265 Record.clear(); 01266 const FileSystemOptions &FSOpts 01267 = Context.getSourceManager().getFileManager().getFileSystemOptions(); 01268 AddString(FSOpts.WorkingDir, Record); 01269 Stream.EmitRecord(FILE_SYSTEM_OPTIONS, Record); 01270 01271 // Header search options. 01272 Record.clear(); 01273 const HeaderSearchOptions &HSOpts 01274 = PP.getHeaderSearchInfo().getHeaderSearchOpts(); 01275 AddString(HSOpts.Sysroot, Record); 01276 01277 // Include entries. 01278 Record.push_back(HSOpts.UserEntries.size()); 01279 for (unsigned I = 0, N = HSOpts.UserEntries.size(); I != N; ++I) { 01280 const HeaderSearchOptions::Entry &Entry = HSOpts.UserEntries[I]; 01281 AddString(Entry.Path, Record); 01282 Record.push_back(static_cast<unsigned>(Entry.Group)); 01283 Record.push_back(Entry.IsFramework); 01284 Record.push_back(Entry.IgnoreSysRoot); 01285 } 01286 01287 // System header prefixes. 01288 Record.push_back(HSOpts.SystemHeaderPrefixes.size()); 01289 for (unsigned I = 0, N = HSOpts.SystemHeaderPrefixes.size(); I != N; ++I) { 01290 AddString(HSOpts.SystemHeaderPrefixes[I].Prefix, Record); 01291 Record.push_back(HSOpts.SystemHeaderPrefixes[I].IsSystemHeader); 01292 } 01293 01294 AddString(HSOpts.ResourceDir, Record); 01295 AddString(HSOpts.ModuleCachePath, Record); 01296 AddString(HSOpts.ModuleUserBuildPath, Record); 01297 Record.push_back(HSOpts.DisableModuleHash); 01298 Record.push_back(HSOpts.UseBuiltinIncludes); 01299 Record.push_back(HSOpts.UseStandardSystemIncludes); 01300 Record.push_back(HSOpts.UseStandardCXXIncludes); 01301 Record.push_back(HSOpts.UseLibcxx); 01302 Stream.EmitRecord(HEADER_SEARCH_OPTIONS, Record); 01303 01304 // Preprocessor options. 01305 Record.clear(); 01306 const PreprocessorOptions &PPOpts = PP.getPreprocessorOpts(); 01307 01308 // Macro definitions. 01309 Record.push_back(PPOpts.Macros.size()); 01310 for (unsigned I = 0, N = PPOpts.Macros.size(); I != N; ++I) { 01311 AddString(PPOpts.Macros[I].first, Record); 01312 Record.push_back(PPOpts.Macros[I].second); 01313 } 01314 01315 // Includes 01316 Record.push_back(PPOpts.Includes.size()); 01317 for (unsigned I = 0, N = PPOpts.Includes.size(); I != N; ++I) 01318 AddString(PPOpts.Includes[I], Record); 01319 01320 // Macro includes 01321 Record.push_back(PPOpts.MacroIncludes.size()); 01322 for (unsigned I = 0, N = PPOpts.MacroIncludes.size(); I != N; ++I) 01323 AddString(PPOpts.MacroIncludes[I], Record); 01324 01325 Record.push_back(PPOpts.UsePredefines); 01326 // Detailed record is important since it is used for the module cache hash. 01327 Record.push_back(PPOpts.DetailedRecord); 01328 AddString(PPOpts.ImplicitPCHInclude, Record); 01329 AddString(PPOpts.ImplicitPTHInclude, Record); 01330 Record.push_back(static_cast<unsigned>(PPOpts.ObjCXXARCStandardLibrary)); 01331 Stream.EmitRecord(PREPROCESSOR_OPTIONS, Record); 01332 01333 // Original file name and file ID 01334 SourceManager &SM = Context.getSourceManager(); 01335 if (const FileEntry *MainFile = SM.getFileEntryForID(SM.getMainFileID())) { 01336 BitCodeAbbrev *FileAbbrev = new BitCodeAbbrev(); 01337 FileAbbrev->Add(BitCodeAbbrevOp(ORIGINAL_FILE)); 01338 FileAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // File ID 01339 FileAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // File name 01340 unsigned FileAbbrevCode = Stream.EmitAbbrev(FileAbbrev); 01341 01342 SmallString<128> MainFilePath(MainFile->getName()); 01343 01344 llvm::sys::fs::make_absolute(MainFilePath); 01345 01346 const char *MainFileNameStr = MainFilePath.c_str(); 01347 MainFileNameStr = adjustFilenameForRelocatablePCH(MainFileNameStr, 01348 isysroot); 01349 Record.clear(); 01350 Record.push_back(ORIGINAL_FILE); 01351 Record.push_back(SM.getMainFileID().getOpaqueValue()); 01352 Stream.EmitRecordWithBlob(FileAbbrevCode, Record, MainFileNameStr); 01353 } 01354 01355 Record.clear(); 01356 Record.push_back(SM.getMainFileID().getOpaqueValue()); 01357 Stream.EmitRecord(ORIGINAL_FILE_ID, Record); 01358 01359 // Original PCH directory 01360 if (!OutputFile.empty() && OutputFile != "-") { 01361 BitCodeAbbrev *Abbrev = new BitCodeAbbrev(); 01362 Abbrev->Add(BitCodeAbbrevOp(ORIGINAL_PCH_DIR)); 01363 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // File name 01364 unsigned AbbrevCode = Stream.EmitAbbrev(Abbrev); 01365 01366 SmallString<128> OutputPath(OutputFile); 01367 01368 llvm::sys::fs::make_absolute(OutputPath); 01369 StringRef origDir = llvm::sys::path::parent_path(OutputPath); 01370 01371 RecordData Record; 01372 Record.push_back(ORIGINAL_PCH_DIR); 01373 Stream.EmitRecordWithBlob(AbbrevCode, Record, origDir); 01374 } 01375 01376 WriteInputFiles(Context.SourceMgr, 01377 PP.getHeaderSearchInfo().getHeaderSearchOpts(), 01378 isysroot, 01379 PP.getLangOpts().Modules); 01380 Stream.ExitBlock(); 01381 } 01382 01383 namespace { 01384 /// \brief An input file. 01385 struct InputFileEntry { 01386 const FileEntry *File; 01387 bool IsSystemFile; 01388 bool BufferOverridden; 01389 }; 01390 } 01391 01392 void ASTWriter::WriteInputFiles(SourceManager &SourceMgr, 01393 HeaderSearchOptions &HSOpts, 01394 StringRef isysroot, 01395 bool Modules) { 01396 using namespace llvm; 01397 Stream.EnterSubblock(INPUT_FILES_BLOCK_ID, 4); 01398 RecordData Record; 01399 01400 // Create input-file abbreviation. 01401 BitCodeAbbrev *IFAbbrev = new BitCodeAbbrev(); 01402 IFAbbrev->Add(BitCodeAbbrevOp(INPUT_FILE)); 01403 IFAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // ID 01404 IFAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 12)); // Size 01405 IFAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 32)); // Modification time 01406 IFAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Overridden 01407 IFAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // File name 01408 unsigned IFAbbrevCode = Stream.EmitAbbrev(IFAbbrev); 01409 01410 // Get all ContentCache objects for files, sorted by whether the file is a 01411 // system one or not. System files go at the back, users files at the front. 01412 std::deque<InputFileEntry> SortedFiles; 01413 for (unsigned I = 1, N = SourceMgr.local_sloc_entry_size(); I != N; ++I) { 01414 // Get this source location entry. 01415 const SrcMgr::SLocEntry *SLoc = &SourceMgr.getLocalSLocEntry(I); 01416 assert(&SourceMgr.getSLocEntry(FileID::get(I)) == SLoc); 01417 01418 // We only care about file entries that were not overridden. 01419 if (!SLoc->isFile()) 01420 continue; 01421 const SrcMgr::ContentCache *Cache = SLoc->getFile().getContentCache(); 01422 if (!Cache->OrigEntry) 01423 continue; 01424 01425 InputFileEntry Entry; 01426 Entry.File = Cache->OrigEntry; 01427 Entry.IsSystemFile = Cache->IsSystemFile; 01428 Entry.BufferOverridden = Cache->BufferOverridden; 01429 if (Cache->IsSystemFile) 01430 SortedFiles.push_back(Entry); 01431 else 01432 SortedFiles.push_front(Entry); 01433 } 01434 01435 unsigned UserFilesNum = 0; 01436 // Write out all of the input files. 01437 std::vector<uint32_t> InputFileOffsets; 01438 for (std::deque<InputFileEntry>::iterator 01439 I = SortedFiles.begin(), E = SortedFiles.end(); I != E; ++I) { 01440 const InputFileEntry &Entry = *I; 01441 01442 uint32_t &InputFileID = InputFileIDs[Entry.File]; 01443 if (InputFileID != 0) 01444 continue; // already recorded this file. 01445 01446 // Record this entry's offset. 01447 InputFileOffsets.push_back(Stream.GetCurrentBitNo()); 01448 01449 InputFileID = InputFileOffsets.size(); 01450 01451 if (!Entry.IsSystemFile) 01452 ++UserFilesNum; 01453 01454 Record.clear(); 01455 Record.push_back(INPUT_FILE); 01456 Record.push_back(InputFileOffsets.size()); 01457 01458 // Emit size/modification time for this file. 01459 Record.push_back(Entry.File->getSize()); 01460 Record.push_back(Entry.File->getModificationTime()); 01461 01462 // Whether this file was overridden. 01463 Record.push_back(Entry.BufferOverridden); 01464 01465 // Turn the file name into an absolute path, if it isn't already. 01466 const char *Filename = Entry.File->getName(); 01467 SmallString<128> FilePath(Filename); 01468 01469 // Ask the file manager to fixup the relative path for us. This will 01470 // honor the working directory. 01471 SourceMgr.getFileManager().FixupRelativePath(FilePath); 01472 01473 // FIXME: This call to make_absolute shouldn't be necessary, the 01474 // call to FixupRelativePath should always return an absolute path. 01475 llvm::sys::fs::make_absolute(FilePath); 01476 Filename = FilePath.c_str(); 01477 01478 Filename = adjustFilenameForRelocatablePCH(Filename, isysroot); 01479 01480 Stream.EmitRecordWithBlob(IFAbbrevCode, Record, Filename); 01481 } 01482 01483 Stream.ExitBlock(); 01484 01485 // Create input file offsets abbreviation. 01486 BitCodeAbbrev *OffsetsAbbrev = new BitCodeAbbrev(); 01487 OffsetsAbbrev->Add(BitCodeAbbrevOp(INPUT_FILE_OFFSETS)); 01488 OffsetsAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // # input files 01489 OffsetsAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // # non-system 01490 // input files 01491 OffsetsAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Array 01492 unsigned OffsetsAbbrevCode = Stream.EmitAbbrev(OffsetsAbbrev); 01493 01494 // Write input file offsets. 01495 Record.clear(); 01496 Record.push_back(INPUT_FILE_OFFSETS); 01497 Record.push_back(InputFileOffsets.size()); 01498 Record.push_back(UserFilesNum); 01499 Stream.EmitRecordWithBlob(OffsetsAbbrevCode, Record, data(InputFileOffsets)); 01500 } 01501 01502 //===----------------------------------------------------------------------===// 01503 // Source Manager Serialization 01504 //===----------------------------------------------------------------------===// 01505 01506 /// \brief Create an abbreviation for the SLocEntry that refers to a 01507 /// file. 01508 static unsigned CreateSLocFileAbbrev(llvm::BitstreamWriter &Stream) { 01509 using namespace llvm; 01510 BitCodeAbbrev *Abbrev = new BitCodeAbbrev(); 01511 Abbrev->Add(BitCodeAbbrevOp(SM_SLOC_FILE_ENTRY)); 01512 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Offset 01513 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Include location 01514 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 2)); // Characteristic 01515 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Line directives 01516 // FileEntry fields. 01517 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Input File ID 01518 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // NumCreatedFIDs 01519 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 24)); // FirstDeclIndex 01520 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // NumDecls 01521 return Stream.EmitAbbrev(Abbrev); 01522 } 01523 01524 /// \brief Create an abbreviation for the SLocEntry that refers to a 01525 /// buffer. 01526 static unsigned CreateSLocBufferAbbrev(llvm::BitstreamWriter &Stream) { 01527 using namespace llvm; 01528 BitCodeAbbrev *Abbrev = new BitCodeAbbrev(); 01529 Abbrev->Add(BitCodeAbbrevOp(SM_SLOC_BUFFER_ENTRY)); 01530 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Offset 01531 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Include location 01532 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 2)); // Characteristic 01533 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Line directives 01534 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Buffer name blob 01535 return Stream.EmitAbbrev(Abbrev); 01536 } 01537 01538 /// \brief Create an abbreviation for the SLocEntry that refers to a 01539 /// buffer's blob. 01540 static unsigned CreateSLocBufferBlobAbbrev(llvm::BitstreamWriter &Stream) { 01541 using namespace llvm; 01542 BitCodeAbbrev *Abbrev = new BitCodeAbbrev(); 01543 Abbrev->Add(BitCodeAbbrevOp(SM_SLOC_BUFFER_BLOB)); 01544 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Blob 01545 return Stream.EmitAbbrev(Abbrev); 01546 } 01547 01548 /// \brief Create an abbreviation for the SLocEntry that refers to a macro 01549 /// expansion. 01550 static unsigned CreateSLocExpansionAbbrev(llvm::BitstreamWriter &Stream) { 01551 using namespace llvm; 01552 BitCodeAbbrev *Abbrev = new BitCodeAbbrev(); 01553 Abbrev->Add(BitCodeAbbrevOp(SM_SLOC_EXPANSION_ENTRY)); 01554 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Offset 01555 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Spelling location 01556 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Start location 01557 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // End location 01558 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Token length 01559 return Stream.EmitAbbrev(Abbrev); 01560 } 01561 01562 namespace { 01563 // Trait used for the on-disk hash table of header search information. 01564 class HeaderFileInfoTrait { 01565 ASTWriter &Writer; 01566 const HeaderSearch &HS; 01567 01568 // Keep track of the framework names we've used during serialization. 01569 SmallVector<char, 128> FrameworkStringData; 01570 llvm::StringMap<unsigned> FrameworkNameOffset; 01571 01572 public: 01573 HeaderFileInfoTrait(ASTWriter &Writer, const HeaderSearch &HS) 01574 : Writer(Writer), HS(HS) { } 01575 01576 struct key_type { 01577 const FileEntry *FE; 01578 const char *Filename; 01579 }; 01580 typedef const key_type &key_type_ref; 01581 01582 typedef HeaderFileInfo data_type; 01583 typedef const data_type &data_type_ref; 01584 typedef unsigned hash_value_type; 01585 typedef unsigned offset_type; 01586 01587 static hash_value_type ComputeHash(key_type_ref key) { 01588 // The hash is based only on size/time of the file, so that the reader can 01589 // match even when symlinking or excess path elements ("foo/../", "../") 01590 // change the form of the name. However, complete path is still the key. 01591 return llvm::hash_combine(key.FE->getSize(), 01592 key.FE->getModificationTime()); 01593 } 01594 01595 std::pair<unsigned,unsigned> 01596 EmitKeyDataLength(raw_ostream& Out, key_type_ref key, data_type_ref Data) { 01597 using namespace llvm::support; 01598 endian::Writer<little> Writer(Out); 01599 unsigned KeyLen = strlen(key.Filename) + 1 + 8 + 8; 01600 Writer.write<uint16_t>(KeyLen); 01601 unsigned DataLen = 1 + 2 + 4 + 4; 01602 if (Data.isModuleHeader) 01603 DataLen += 4; 01604 Writer.write<uint8_t>(DataLen); 01605 return std::make_pair(KeyLen, DataLen); 01606 } 01607 01608 void EmitKey(raw_ostream& Out, key_type_ref key, unsigned KeyLen) { 01609 using namespace llvm::support; 01610 endian::Writer<little> LE(Out); 01611 LE.write<uint64_t>(key.FE->getSize()); 01612 KeyLen -= 8; 01613 LE.write<uint64_t>(key.FE->getModificationTime()); 01614 KeyLen -= 8; 01615 Out.write(key.Filename, KeyLen); 01616 } 01617 01618 void EmitData(raw_ostream &Out, key_type_ref key, 01619 data_type_ref Data, unsigned DataLen) { 01620 using namespace llvm::support; 01621 endian::Writer<little> LE(Out); 01622 uint64_t Start = Out.tell(); (void)Start; 01623 01624 unsigned char Flags = (Data.HeaderRole << 6) 01625 | (Data.isImport << 5) 01626 | (Data.isPragmaOnce << 4) 01627 | (Data.DirInfo << 2) 01628 | (Data.Resolved << 1) 01629 | Data.IndexHeaderMapHeader; 01630 LE.write<uint8_t>(Flags); 01631 LE.write<uint16_t>(Data.NumIncludes); 01632 01633 if (!Data.ControllingMacro) 01634 LE.write<uint32_t>(Data.ControllingMacroID); 01635 else 01636 LE.write<uint32_t>(Writer.getIdentifierRef(Data.ControllingMacro)); 01637 01638 unsigned Offset = 0; 01639 if (!Data.Framework.empty()) { 01640 // If this header refers into a framework, save the framework name. 01641 llvm::StringMap<unsigned>::iterator Pos 01642 = FrameworkNameOffset.find(Data.Framework); 01643 if (Pos == FrameworkNameOffset.end()) { 01644 Offset = FrameworkStringData.size() + 1; 01645 FrameworkStringData.append(Data.Framework.begin(), 01646 Data.Framework.end()); 01647 FrameworkStringData.push_back(0); 01648 01649 FrameworkNameOffset[Data.Framework] = Offset; 01650 } else 01651 Offset = Pos->second; 01652 } 01653 LE.write<uint32_t>(Offset); 01654 01655 if (Data.isModuleHeader) { 01656 Module *Mod = HS.findModuleForHeader(key.FE).getModule(); 01657 LE.write<uint32_t>(Writer.getExistingSubmoduleID(Mod)); 01658 } 01659 01660 assert(Out.tell() - Start == DataLen && "Wrong data length"); 01661 } 01662 01663 const char *strings_begin() const { return FrameworkStringData.begin(); } 01664 const char *strings_end() const { return FrameworkStringData.end(); } 01665 }; 01666 } // end anonymous namespace 01667 01668 /// \brief Write the header search block for the list of files that 01669 /// 01670 /// \param HS The header search structure to save. 01671 void ASTWriter::WriteHeaderSearch(const HeaderSearch &HS, StringRef isysroot) { 01672 SmallVector<const FileEntry *, 16> FilesByUID; 01673 HS.getFileMgr().GetUniqueIDMapping(FilesByUID); 01674 01675 if (FilesByUID.size() > HS.header_file_size()) 01676 FilesByUID.resize(HS.header_file_size()); 01677 01678 HeaderFileInfoTrait GeneratorTrait(*this, HS); 01679 llvm::OnDiskChainedHashTableGenerator<HeaderFileInfoTrait> Generator; 01680 SmallVector<const char *, 4> SavedStrings; 01681 unsigned NumHeaderSearchEntries = 0; 01682 for (unsigned UID = 0, LastUID = FilesByUID.size(); UID != LastUID; ++UID) { 01683 const FileEntry *File = FilesByUID[UID]; 01684 if (!File) 01685 continue; 01686 01687 // Use HeaderSearch's getFileInfo to make sure we get the HeaderFileInfo 01688 // from the external source if it was not provided already. 01689 HeaderFileInfo HFI; 01690 if (!HS.tryGetFileInfo(File, HFI) || 01691 (HFI.External && Chain) || 01692 (HFI.isModuleHeader && !HFI.isCompilingModuleHeader)) 01693 continue; 01694 01695 // Turn the file name into an absolute path, if it isn't already. 01696 const char *Filename = File->getName(); 01697 Filename = adjustFilenameForRelocatablePCH(Filename, isysroot); 01698 01699 // If we performed any translation on the file name at all, we need to 01700 // save this string, since the generator will refer to it later. 01701 if (Filename != File->getName()) { 01702 Filename = strdup(Filename); 01703 SavedStrings.push_back(Filename); 01704 } 01705 01706 HeaderFileInfoTrait::key_type key = { File, Filename }; 01707 Generator.insert(key, HFI, GeneratorTrait); 01708 ++NumHeaderSearchEntries; 01709 } 01710 01711 // Create the on-disk hash table in a buffer. 01712 SmallString<4096> TableData; 01713 uint32_t BucketOffset; 01714 { 01715 using namespace llvm::support; 01716 llvm::raw_svector_ostream Out(TableData); 01717 // Make sure that no bucket is at offset 0 01718 endian::Writer<little>(Out).write<uint32_t>(0); 01719 BucketOffset = Generator.Emit(Out, GeneratorTrait); 01720 } 01721 01722 // Create a blob abbreviation 01723 using namespace llvm; 01724 BitCodeAbbrev *Abbrev = new BitCodeAbbrev(); 01725 Abbrev->Add(BitCodeAbbrevOp(HEADER_SEARCH_TABLE)); 01726 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); 01727 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); 01728 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); 01729 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); 01730 unsigned TableAbbrev = Stream.EmitAbbrev(Abbrev); 01731 01732 // Write the header search table 01733 RecordData Record; 01734 Record.push_back(HEADER_SEARCH_TABLE); 01735 Record.push_back(BucketOffset); 01736 Record.push_back(NumHeaderSearchEntries); 01737 Record.push_back(TableData.size()); 01738 TableData.append(GeneratorTrait.strings_begin(),GeneratorTrait.strings_end()); 01739 Stream.EmitRecordWithBlob(TableAbbrev, Record, TableData.str()); 01740 01741 // Free all of the strings we had to duplicate. 01742 for (unsigned I = 0, N = SavedStrings.size(); I != N; ++I) 01743 free(const_cast<char *>(SavedStrings[I])); 01744 } 01745 01746 /// \brief Writes the block containing the serialized form of the 01747 /// source manager. 01748 /// 01749 /// TODO: We should probably use an on-disk hash table (stored in a 01750 /// blob), indexed based on the file name, so that we only create 01751 /// entries for files that we actually need. In the common case (no 01752 /// errors), we probably won't have to create file entries for any of 01753 /// the files in the AST. 01754 void ASTWriter::WriteSourceManagerBlock(SourceManager &SourceMgr, 01755 const Preprocessor &PP, 01756 StringRef isysroot) { 01757 RecordData Record; 01758 01759 // Enter the source manager block. 01760 Stream.EnterSubblock(SOURCE_MANAGER_BLOCK_ID, 3); 01761 01762 // Abbreviations for the various kinds of source-location entries. 01763 unsigned SLocFileAbbrv = CreateSLocFileAbbrev(Stream); 01764 unsigned SLocBufferAbbrv = CreateSLocBufferAbbrev(Stream); 01765 unsigned SLocBufferBlobAbbrv = CreateSLocBufferBlobAbbrev(Stream); 01766 unsigned SLocExpansionAbbrv = CreateSLocExpansionAbbrev(Stream); 01767 01768 // Write out the source location entry table. We skip the first 01769 // entry, which is always the same dummy entry. 01770 std::vector<uint32_t> SLocEntryOffsets; 01771 RecordData PreloadSLocs; 01772 SLocEntryOffsets.reserve(SourceMgr.local_sloc_entry_size() - 1); 01773 for (unsigned I = 1, N = SourceMgr.local_sloc_entry_size(); 01774 I != N; ++I) { 01775 // Get this source location entry. 01776 const SrcMgr::SLocEntry *SLoc = &SourceMgr.getLocalSLocEntry(I); 01777 FileID FID = FileID::get(I); 01778 assert(&SourceMgr.getSLocEntry(FID) == SLoc); 01779 01780 // Record the offset of this source-location entry. 01781 SLocEntryOffsets.push_back(Stream.GetCurrentBitNo()); 01782 01783 // Figure out which record code to use. 01784 unsigned Code; 01785 if (SLoc->isFile()) { 01786 const SrcMgr::ContentCache *Cache = SLoc->getFile().getContentCache(); 01787 if (Cache->OrigEntry) { 01788 Code = SM_SLOC_FILE_ENTRY; 01789 } else 01790 Code = SM_SLOC_BUFFER_ENTRY; 01791 } else 01792 Code = SM_SLOC_EXPANSION_ENTRY; 01793 Record.clear(); 01794 Record.push_back(Code); 01795 01796 // Starting offset of this entry within this module, so skip the dummy. 01797 Record.push_back(SLoc->getOffset() - 2); 01798 if (SLoc->isFile()) { 01799 const SrcMgr::FileInfo &File = SLoc->getFile(); 01800 Record.push_back(File.getIncludeLoc().getRawEncoding()); 01801 Record.push_back(File.getFileCharacteristic()); // FIXME: stable encoding 01802 Record.push_back(File.hasLineDirectives()); 01803 01804 const SrcMgr::ContentCache *Content = File.getContentCache(); 01805 if (Content->OrigEntry) { 01806 assert(Content->OrigEntry == Content->ContentsEntry && 01807 "Writing to AST an overridden file is not supported"); 01808 01809 // The source location entry is a file. Emit input file ID. 01810 assert(InputFileIDs[Content->OrigEntry] != 0 && "Missed file entry"); 01811 Record.push_back(InputFileIDs[Content->OrigEntry]); 01812 01813 Record.push_back(File.NumCreatedFIDs); 01814 01815 FileDeclIDsTy::iterator FDI = FileDeclIDs.find(FID); 01816 if (FDI != FileDeclIDs.end()) { 01817 Record.push_back(FDI->second->FirstDeclIndex); 01818 Record.push_back(FDI->second->DeclIDs.size()); 01819 } else { 01820 Record.push_back(0); 01821 Record.push_back(0); 01822 } 01823 01824 Stream.EmitRecordWithAbbrev(SLocFileAbbrv, Record); 01825 01826 if (Content->BufferOverridden) { 01827 Record.clear(); 01828 Record.push_back(SM_SLOC_BUFFER_BLOB); 01829 const llvm::MemoryBuffer *Buffer 01830 = Content->getBuffer(PP.getDiagnostics(), PP.getSourceManager()); 01831 Stream.EmitRecordWithBlob(SLocBufferBlobAbbrv, Record, 01832 StringRef(Buffer->getBufferStart(), 01833 Buffer->getBufferSize() + 1)); 01834 } 01835 } else { 01836 // The source location entry is a buffer. The blob associated 01837 // with this entry contains the contents of the buffer. 01838 01839 // We add one to the size so that we capture the trailing NULL 01840 // that is required by llvm::MemoryBuffer::getMemBuffer (on 01841 // the reader side). 01842 const llvm::MemoryBuffer *Buffer 01843 = Content->getBuffer(PP.getDiagnostics(), PP.getSourceManager()); 01844 const char *Name = Buffer->getBufferIdentifier(); 01845 Stream.EmitRecordWithBlob(SLocBufferAbbrv, Record, 01846 StringRef(Name, strlen(Name) + 1)); 01847 Record.clear(); 01848 Record.push_back(SM_SLOC_BUFFER_BLOB); 01849 Stream.EmitRecordWithBlob(SLocBufferBlobAbbrv, Record, 01850 StringRef(Buffer->getBufferStart(), 01851 Buffer->getBufferSize() + 1)); 01852 01853 if (strcmp(Name, "<built-in>") == 0) { 01854 PreloadSLocs.push_back(SLocEntryOffsets.size()); 01855 } 01856 } 01857 } else { 01858 // The source location entry is a macro expansion. 01859 const SrcMgr::ExpansionInfo &Expansion = SLoc->getExpansion(); 01860 Record.push_back(Expansion.getSpellingLoc().getRawEncoding()); 01861 Record.push_back(Expansion.getExpansionLocStart().getRawEncoding()); 01862 Record.push_back(Expansion.isMacroArgExpansion() ? 0 01863 : Expansion.getExpansionLocEnd().getRawEncoding()); 01864 01865 // Compute the token length for this macro expansion. 01866 unsigned NextOffset = SourceMgr.getNextLocalOffset(); 01867 if (I + 1 != N) 01868 NextOffset = SourceMgr.getLocalSLocEntry(I + 1).getOffset(); 01869 Record.push_back(NextOffset - SLoc->getOffset() - 1); 01870 Stream.EmitRecordWithAbbrev(SLocExpansionAbbrv, Record); 01871 } 01872 } 01873 01874 Stream.ExitBlock(); 01875 01876 if (SLocEntryOffsets.empty()) 01877 return; 01878 01879 // Write the source-location offsets table into the AST block. This 01880 // table is used for lazily loading source-location information. 01881 using namespace llvm; 01882 BitCodeAbbrev *Abbrev = new BitCodeAbbrev(); 01883 Abbrev->Add(BitCodeAbbrevOp(SOURCE_LOCATION_OFFSETS)); 01884 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 16)); // # of slocs 01885 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 16)); // total size 01886 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // offsets 01887 unsigned SLocOffsetsAbbrev = Stream.EmitAbbrev(Abbrev); 01888 01889 Record.clear(); 01890 Record.push_back(SOURCE_LOCATION_OFFSETS); 01891 Record.push_back(SLocEntryOffsets.size()); 01892 Record.push_back(SourceMgr.getNextLocalOffset() - 1); // skip dummy 01893 Stream.EmitRecordWithBlob(SLocOffsetsAbbrev, Record, data(SLocEntryOffsets)); 01894 01895 // Write the source location entry preloads array, telling the AST 01896 // reader which source locations entries it should load eagerly. 01897 Stream.EmitRecord(SOURCE_LOCATION_PRELOADS, PreloadSLocs); 01898 01899 // Write the line table. It depends on remapping working, so it must come 01900 // after the source location offsets. 01901 if (SourceMgr.hasLineTable()) { 01902 LineTableInfo &LineTable = SourceMgr.getLineTable(); 01903 01904 Record.clear(); 01905 // Emit the file names 01906 Record.push_back(LineTable.getNumFilenames()); 01907 for (unsigned I = 0, N = LineTable.getNumFilenames(); I != N; ++I) { 01908 // Emit the file name 01909 const char *Filename = LineTable.getFilename(I); 01910 Filename = adjustFilenameForRelocatablePCH(Filename, isysroot); 01911 unsigned FilenameLen = Filename? strlen(Filename) : 0; 01912 Record.push_back(FilenameLen); 01913 if (FilenameLen) 01914 Record.insert(Record.end(), Filename, Filename + FilenameLen); 01915 } 01916 01917 // Emit the line entries 01918 for (LineTableInfo::iterator L = LineTable.begin(), LEnd = LineTable.end(); 01919 L != LEnd; ++L) { 01920 // Only emit entries for local files. 01921 if (L->first.ID < 0) 01922 continue; 01923 01924 // Emit the file ID 01925 Record.push_back(L->first.ID); 01926 01927 // Emit the line entries 01928 Record.push_back(L->second.size()); 01929 for (std::vector<LineEntry>::iterator LE = L->second.begin(), 01930 LEEnd = L->second.end(); 01931 LE != LEEnd; ++LE) { 01932 Record.push_back(LE->FileOffset); 01933 Record.push_back(LE->LineNo); 01934 Record.push_back(LE->FilenameID); 01935 Record.push_back((unsigned)LE->FileKind); 01936 Record.push_back(LE->IncludeOffset); 01937 } 01938 } 01939 Stream.EmitRecord(SOURCE_MANAGER_LINE_TABLE, Record); 01940 } 01941 } 01942 01943 //===----------------------------------------------------------------------===// 01944 // Preprocessor Serialization 01945 //===----------------------------------------------------------------------===// 01946 01947 namespace { 01948 class ASTMacroTableTrait { 01949 public: 01950 typedef IdentID key_type; 01951 typedef key_type key_type_ref; 01952 01953 struct Data { 01954 uint32_t MacroDirectivesOffset; 01955 }; 01956 01957 typedef Data data_type; 01958 typedef const data_type &data_type_ref; 01959 typedef unsigned hash_value_type; 01960 typedef unsigned offset_type; 01961 01962 static hash_value_type ComputeHash(IdentID IdID) { 01963 return llvm::hash_value(IdID); 01964 } 01965 01966 std::pair<unsigned,unsigned> 01967 static EmitKeyDataLength(raw_ostream& Out, 01968 key_type_ref Key, data_type_ref Data) { 01969 unsigned KeyLen = 4; // IdentID. 01970 unsigned DataLen = 4; // MacroDirectivesOffset. 01971 return std::make_pair(KeyLen, DataLen); 01972 } 01973 01974 static void EmitKey(raw_ostream& Out, key_type_ref Key, unsigned KeyLen) { 01975 using namespace llvm::support; 01976 endian::Writer<little>(Out).write<uint32_t>(Key); 01977 } 01978 01979 static void EmitData(raw_ostream& Out, key_type_ref Key, data_type_ref Data, 01980 unsigned) { 01981 using namespace llvm::support; 01982 endian::Writer<little>(Out).write<uint32_t>(Data.MacroDirectivesOffset); 01983 } 01984 }; 01985 } // end anonymous namespace 01986 01987 static int compareMacroDirectives( 01988 const std::pair<const IdentifierInfo *, MacroDirective *> *X, 01989 const std::pair<const IdentifierInfo *, MacroDirective *> *Y) { 01990 return X->first->getName().compare(Y->first->getName()); 01991 } 01992 01993 static bool shouldIgnoreMacro(MacroDirective *MD, bool IsModule, 01994 const Preprocessor &PP) { 01995 if (MacroInfo *MI = MD->getMacroInfo()) 01996 if (MI->isBuiltinMacro()) 01997 return true; 01998 01999 if (IsModule) { 02000 // Re-export any imported directives. 02001 if (MD->isImported()) 02002 return false; 02003 02004 SourceLocation Loc = MD->getLocation(); 02005 if (Loc.isInvalid()) 02006 return true; 02007 if (PP.getSourceManager().getFileID(Loc) == PP.getPredefinesFileID()) 02008 return true; 02009 } 02010 02011 return false; 02012 } 02013 02014 /// \brief Writes the block containing the serialized form of the 02015 /// preprocessor. 02016 /// 02017 void ASTWriter::WritePreprocessor(const Preprocessor &PP, bool IsModule) { 02018 PreprocessingRecord *PPRec = PP.getPreprocessingRecord(); 02019 if (PPRec) 02020 WritePreprocessorDetail(*PPRec); 02021 02022 RecordData Record; 02023 02024 // If the preprocessor __COUNTER__ value has been bumped, remember it. 02025 if (PP.getCounterValue() != 0) { 02026 Record.push_back(PP.getCounterValue()); 02027 Stream.EmitRecord(PP_COUNTER_VALUE, Record); 02028 Record.clear(); 02029 } 02030 02031 // Enter the preprocessor block. 02032 Stream.EnterSubblock(PREPROCESSOR_BLOCK_ID, 3); 02033 02034 // If the AST file contains __DATE__ or __TIME__ emit a warning about this. 02035 // FIXME: use diagnostics subsystem for localization etc. 02036 if (PP.SawDateOrTime()) 02037 fprintf(stderr, "warning: precompiled header used __DATE__ or __TIME__.\n"); 02038 02039 02040 // Loop over all the macro directives that are live at the end of the file, 02041 // emitting each to the PP section. 02042 02043 // Construct the list of macro directives that need to be serialized. 02044 SmallVector<std::pair<const IdentifierInfo *, MacroDirective *>, 2> 02045 MacroDirectives; 02046 for (Preprocessor::macro_iterator 02047 I = PP.macro_begin(/*IncludeExternalMacros=*/false), 02048 E = PP.macro_end(/*IncludeExternalMacros=*/false); 02049 I != E; ++I) { 02050 MacroDirectives.push_back(std::make_pair(I->first, I->second)); 02051 } 02052 02053 // Sort the set of macro definitions that need to be serialized by the 02054 // name of the macro, to provide a stable ordering. 02055 llvm::array_pod_sort(MacroDirectives.begin(), MacroDirectives.end(), 02056 &compareMacroDirectives); 02057 02058 llvm::OnDiskChainedHashTableGenerator<ASTMacroTableTrait> Generator; 02059 02060 // Emit the macro directives as a list and associate the offset with the 02061 // identifier they belong to. 02062 for (unsigned I = 0, N = MacroDirectives.size(); I != N; ++I) { 02063 const IdentifierInfo *Name = MacroDirectives[I].first; 02064 uint64_t MacroDirectiveOffset = Stream.GetCurrentBitNo(); 02065 MacroDirective *MD = MacroDirectives[I].second; 02066 02067 // If the macro or identifier need no updates, don't write the macro history 02068 // for this one. 02069 // FIXME: Chain the macro history instead of re-writing it. 02070 if (MD->isFromPCH() && 02071 Name->isFromAST() && !Name->hasChangedSinceDeserialization()) 02072 continue; 02073 02074 // Emit the macro directives in reverse source order. 02075 for (; MD; MD = MD->getPrevious()) { 02076 if (shouldIgnoreMacro(MD, IsModule, PP)) 02077 continue; 02078 02079 AddSourceLocation(MD->getLocation(), Record); 02080 Record.push_back(MD->getKind()); 02081 if (auto *DefMD = dyn_cast<DefMacroDirective>(MD)) { 02082 MacroID InfoID = getMacroRef(DefMD->getInfo(), Name); 02083 Record.push_back(InfoID); 02084 Record.push_back(DefMD->getOwningModuleID()); 02085 Record.push_back(DefMD->isAmbiguous()); 02086 } else if (auto *UndefMD = dyn_cast<UndefMacroDirective>(MD)) { 02087 Record.push_back(UndefMD->getOwningModuleID()); 02088 } else { 02089 auto *VisMD = cast<VisibilityMacroDirective>(MD); 02090 Record.push_back(VisMD->isPublic()); 02091 } 02092 02093 if (MD->isImported()) { 02094 auto Overrides = MD->getOverriddenModules(); 02095 Record.push_back(Overrides.size()); 02096 for (auto Override : Overrides) 02097 Record.push_back(Override); 02098 } 02099 } 02100 if (Record.empty()) 02101 continue; 02102 02103 Stream.EmitRecord(PP_MACRO_DIRECTIVE_HISTORY, Record); 02104 Record.clear(); 02105 02106 IdentMacroDirectivesOffsetMap[Name] = MacroDirectiveOffset; 02107 02108 IdentID NameID = getIdentifierRef(Name); 02109 ASTMacroTableTrait::Data data; 02110 data.MacroDirectivesOffset = MacroDirectiveOffset; 02111 Generator.insert(NameID, data); 02112 } 02113 02114 /// \brief Offsets of each of the macros into the bitstream, indexed by 02115 /// the local macro ID 02116 /// 02117 /// For each identifier that is associated with a macro, this map 02118 /// provides the offset into the bitstream where that macro is 02119 /// defined. 02120 std::vector<uint32_t> MacroOffsets; 02121 02122 for (unsigned I = 0, N = MacroInfosToEmit.size(); I != N; ++I) { 02123 const IdentifierInfo *Name = MacroInfosToEmit[I].Name; 02124 MacroInfo *MI = MacroInfosToEmit[I].MI; 02125 MacroID ID = MacroInfosToEmit[I].ID; 02126 02127 if (ID < FirstMacroID) { 02128 assert(0 && "Loaded MacroInfo entered MacroInfosToEmit ?"); 02129 continue; 02130 } 02131 02132 // Record the local offset of this macro. 02133 unsigned Index = ID - FirstMacroID; 02134 if (Index == MacroOffsets.size()) 02135 MacroOffsets.push_back(Stream.GetCurrentBitNo()); 02136 else { 02137 if (Index > MacroOffsets.size()) 02138 MacroOffsets.resize(Index + 1); 02139 02140 MacroOffsets[Index] = Stream.GetCurrentBitNo(); 02141 } 02142 02143 AddIdentifierRef(Name, Record); 02144 Record.push_back(inferSubmoduleIDFromLocation(MI->getDefinitionLoc())); 02145 AddSourceLocation(MI->getDefinitionLoc(), Record); 02146 AddSourceLocation(MI->getDefinitionEndLoc(), Record); 02147 Record.push_back(MI->isUsed()); 02148 Record.push_back(MI->isUsedForHeaderGuard()); 02149 unsigned Code; 02150 if (MI->isObjectLike()) { 02151 Code = PP_MACRO_OBJECT_LIKE; 02152 } else { 02153 Code = PP_MACRO_FUNCTION_LIKE; 02154 02155 Record.push_back(MI->isC99Varargs()); 02156 Record.push_back(MI->isGNUVarargs()); 02157 Record.push_back(MI->hasCommaPasting()); 02158 Record.push_back(MI->getNumArgs()); 02159 for (MacroInfo::arg_iterator I = MI->arg_begin(), E = MI->arg_end(); 02160 I != E; ++I) 02161 AddIdentifierRef(*I, Record); 02162 } 02163 02164 // If we have a detailed preprocessing record, record the macro definition 02165 // ID that corresponds to this macro. 02166 if (PPRec) 02167 Record.push_back(MacroDefinitions[PPRec->findMacroDefinition(MI)]); 02168 02169 Stream.EmitRecord(Code, Record); 02170 Record.clear(); 02171 02172 // Emit the tokens array. 02173 for (unsigned TokNo = 0, e = MI->getNumTokens(); TokNo != e; ++TokNo) { 02174 // Note that we know that the preprocessor does not have any annotation 02175 // tokens in it because they are created by the parser, and thus can't 02176 // be in a macro definition. 02177 const Token &Tok = MI->getReplacementToken(TokNo); 02178 AddToken(Tok, Record); 02179 Stream.EmitRecord(PP_TOKEN, Record); 02180 Record.clear(); 02181 } 02182 ++NumMacros; 02183 } 02184 02185 Stream.ExitBlock(); 02186 02187 // Create the on-disk hash table in a buffer. 02188 SmallString<4096> MacroTable; 02189 uint32_t BucketOffset; 02190 { 02191 using namespace llvm::support; 02192 llvm::raw_svector_ostream Out(MacroTable); 02193 // Make sure that no bucket is at offset 0 02194 endian::Writer<little>(Out).write<uint32_t>(0); 02195 BucketOffset = Generator.Emit(Out); 02196 } 02197 02198 // Write the macro table 02199 using namespace llvm; 02200 BitCodeAbbrev *Abbrev = new BitCodeAbbrev(); 02201 Abbrev->Add(BitCodeAbbrevOp(MACRO_TABLE)); 02202 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); 02203 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); 02204 unsigned MacroTableAbbrev = Stream.EmitAbbrev(Abbrev); 02205 02206 Record.push_back(MACRO_TABLE); 02207 Record.push_back(BucketOffset); 02208 Stream.EmitRecordWithBlob(MacroTableAbbrev, Record, MacroTable.str()); 02209 Record.clear(); 02210 02211 // Write the offsets table for macro IDs. 02212 using namespace llvm; 02213 Abbrev = new BitCodeAbbrev(); 02214 Abbrev->Add(BitCodeAbbrevOp(MACRO_OFFSET)); 02215 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // # of macros 02216 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // first ID 02217 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); 02218 02219 unsigned MacroOffsetAbbrev = Stream.EmitAbbrev(Abbrev); 02220 Record.clear(); 02221 Record.push_back(MACRO_OFFSET); 02222 Record.push_back(MacroOffsets.size()); 02223 Record.push_back(FirstMacroID - NUM_PREDEF_MACRO_IDS); 02224 Stream.EmitRecordWithBlob(MacroOffsetAbbrev, Record, 02225 data(MacroOffsets)); 02226 } 02227 02228 void ASTWriter::WritePreprocessorDetail(PreprocessingRecord &PPRec) { 02229 if (PPRec.local_begin() == PPRec.local_end()) 02230 return; 02231 02232 SmallVector<PPEntityOffset, 64> PreprocessedEntityOffsets; 02233 02234 // Enter the preprocessor block. 02235 Stream.EnterSubblock(PREPROCESSOR_DETAIL_BLOCK_ID, 3); 02236 02237 // If the preprocessor has a preprocessing record, emit it. 02238 unsigned NumPreprocessingRecords = 0; 02239 using namespace llvm; 02240 02241 // Set up the abbreviation for 02242 unsigned InclusionAbbrev = 0; 02243 { 02244 BitCodeAbbrev *Abbrev = new BitCodeAbbrev(); 02245 Abbrev->Add(BitCodeAbbrevOp(PPD_INCLUSION_DIRECTIVE)); 02246 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // filename length 02247 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // in quotes 02248 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 2)); // kind 02249 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // imported module 02250 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); 02251 InclusionAbbrev = Stream.EmitAbbrev(Abbrev); 02252 } 02253 02254 unsigned FirstPreprocessorEntityID 02255 = (Chain ? PPRec.getNumLoadedPreprocessedEntities() : 0) 02256 + NUM_PREDEF_PP_ENTITY_IDS; 02257 unsigned NextPreprocessorEntityID = FirstPreprocessorEntityID; 02258 RecordData Record; 02259 for (PreprocessingRecord::iterator E = PPRec.local_begin(), 02260 EEnd = PPRec.local_end(); 02261 E != EEnd; 02262 (void)++E, ++NumPreprocessingRecords, ++NextPreprocessorEntityID) { 02263 Record.clear(); 02264 02265 PreprocessedEntityOffsets.push_back(PPEntityOffset((*E)->getSourceRange(), 02266 Stream.GetCurrentBitNo())); 02267 02268 if (MacroDefinition *MD = dyn_cast<MacroDefinition>(*E)) { 02269 // Record this macro definition's ID. 02270 MacroDefinitions[MD] = NextPreprocessorEntityID; 02271 02272 AddIdentifierRef(MD->getName(), Record); 02273 Stream.EmitRecord(PPD_MACRO_DEFINITION, Record); 02274 continue; 02275 } 02276 02277 if (MacroExpansion *ME = dyn_cast<MacroExpansion>(*E)) { 02278 Record.push_back(ME->isBuiltinMacro()); 02279 if (ME->isBuiltinMacro()) 02280 AddIdentifierRef(ME->getName(), Record); 02281 else 02282 Record.push_back(MacroDefinitions[ME->getDefinition()]); 02283 Stream.EmitRecord(PPD_MACRO_EXPANSION, Record); 02284 continue; 02285 } 02286 02287 if (InclusionDirective *ID = dyn_cast<InclusionDirective>(*E)) { 02288 Record.push_back(PPD_INCLUSION_DIRECTIVE); 02289 Record.push_back(ID->getFileName().size()); 02290 Record.push_back(ID->wasInQuotes()); 02291 Record.push_back(static_cast<unsigned>(ID->getKind())); 02292 Record.push_back(ID->importedModule()); 02293 SmallString<64> Buffer; 02294 Buffer += ID->getFileName(); 02295 // Check that the FileEntry is not null because it was not resolved and 02296 // we create a PCH even with compiler errors. 02297 if (ID->getFile()) 02298 Buffer += ID->getFile()->getName(); 02299 Stream.EmitRecordWithBlob(InclusionAbbrev, Record, Buffer); 02300 continue; 02301 } 02302 02303 llvm_unreachable("Unhandled PreprocessedEntity in ASTWriter"); 02304 } 02305 Stream.ExitBlock(); 02306 02307 // Write the offsets table for the preprocessing record. 02308 if (NumPreprocessingRecords > 0) { 02309 assert(PreprocessedEntityOffsets.size() == NumPreprocessingRecords); 02310 02311 // Write the offsets table for identifier IDs. 02312 using namespace llvm; 02313 BitCodeAbbrev *Abbrev = new BitCodeAbbrev(); 02314 Abbrev->Add(BitCodeAbbrevOp(PPD_ENTITIES_OFFSETS)); 02315 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // first pp entity 02316 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); 02317 unsigned PPEOffsetAbbrev = Stream.EmitAbbrev(Abbrev); 02318 02319 Record.clear(); 02320 Record.push_back(PPD_ENTITIES_OFFSETS); 02321 Record.push_back(FirstPreprocessorEntityID - NUM_PREDEF_PP_ENTITY_IDS); 02322 Stream.EmitRecordWithBlob(PPEOffsetAbbrev, Record, 02323 data(PreprocessedEntityOffsets)); 02324 } 02325 } 02326 02327 unsigned ASTWriter::getSubmoduleID(Module *Mod) { 02328 llvm::DenseMap<Module *, unsigned>::iterator Known = SubmoduleIDs.find(Mod); 02329 if (Known != SubmoduleIDs.end()) 02330 return Known->second; 02331 02332 return SubmoduleIDs[Mod] = NextSubmoduleID++; 02333 } 02334 02335 unsigned ASTWriter::getExistingSubmoduleID(Module *Mod) const { 02336 if (!Mod) 02337 return 0; 02338 02339 llvm::DenseMap<Module *, unsigned>::const_iterator 02340 Known = SubmoduleIDs.find(Mod); 02341 if (Known != SubmoduleIDs.end()) 02342 return Known->second; 02343 02344 return 0; 02345 } 02346 02347 /// \brief Compute the number of modules within the given tree (including the 02348 /// given module). 02349 static unsigned getNumberOfModules(Module *Mod) { 02350 unsigned ChildModules = 0; 02351 for (Module::submodule_iterator Sub = Mod->submodule_begin(), 02352 SubEnd = Mod->submodule_end(); 02353 Sub != SubEnd; ++Sub) 02354 ChildModules += getNumberOfModules(*Sub); 02355 02356 return ChildModules + 1; 02357 } 02358 02359 void ASTWriter::WriteSubmodules(Module *WritingModule) { 02360 // Determine the dependencies of our module and each of it's submodules. 02361 // FIXME: This feels like it belongs somewhere else, but there are no 02362 // other consumers of this information. 02363 SourceManager &SrcMgr = PP->getSourceManager(); 02364 ModuleMap &ModMap = PP->getHeaderSearchInfo().getModuleMap(); 02365 for (const auto *I : Context->local_imports()) { 02366 if (Module *ImportedFrom 02367 = ModMap.inferModuleFromLocation(FullSourceLoc(I->getLocation(), 02368 SrcMgr))) { 02369 ImportedFrom->Imports.push_back(I->getImportedModule()); 02370 } 02371 } 02372 02373 // Enter the submodule description block. 02374 Stream.EnterSubblock(SUBMODULE_BLOCK_ID, /*bits for abbreviations*/5); 02375 02376 // Write the abbreviations needed for the submodules block. 02377 using namespace llvm; 02378 BitCodeAbbrev *Abbrev = new BitCodeAbbrev(); 02379 Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_DEFINITION)); 02380 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // ID 02381 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Parent 02382 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // IsFramework 02383 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // IsExplicit 02384 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // IsSystem 02385 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // IsExternC 02386 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // InferSubmodules... 02387 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // InferExplicit... 02388 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // InferExportWild... 02389 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // ConfigMacrosExh... 02390 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name 02391 unsigned DefinitionAbbrev = Stream.EmitAbbrev(Abbrev); 02392 02393 Abbrev = new BitCodeAbbrev(); 02394 Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_UMBRELLA_HEADER)); 02395 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name 02396 unsigned UmbrellaAbbrev = Stream.EmitAbbrev(Abbrev); 02397 02398 Abbrev = new BitCodeAbbrev(); 02399 Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_HEADER)); 02400 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name 02401 unsigned HeaderAbbrev = Stream.EmitAbbrev(Abbrev); 02402 02403 Abbrev = new BitCodeAbbrev(); 02404 Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_TOPHEADER)); 02405 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name 02406 unsigned TopHeaderAbbrev = Stream.EmitAbbrev(Abbrev); 02407 02408 Abbrev = new BitCodeAbbrev(); 02409 Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_UMBRELLA_DIR)); 02410 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name 02411 unsigned UmbrellaDirAbbrev = Stream.EmitAbbrev(Abbrev); 02412 02413 Abbrev = new BitCodeAbbrev(); 02414 Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_REQUIRES)); 02415 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // State 02416 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Feature 02417 unsigned RequiresAbbrev = Stream.EmitAbbrev(Abbrev); 02418 02419 Abbrev = new BitCodeAbbrev(); 02420 Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_EXCLUDED_HEADER)); 02421 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name 02422 unsigned ExcludedHeaderAbbrev = Stream.EmitAbbrev(Abbrev); 02423 02424 Abbrev = new BitCodeAbbrev(); 02425 Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_TEXTUAL_HEADER)); 02426 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name 02427 unsigned TextualHeaderAbbrev = Stream.EmitAbbrev(Abbrev); 02428 02429 Abbrev = new BitCodeAbbrev(); 02430 Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_PRIVATE_HEADER)); 02431 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name 02432 unsigned PrivateHeaderAbbrev = Stream.EmitAbbrev(Abbrev); 02433 02434 Abbrev = new BitCodeAbbrev(); 02435 Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_PRIVATE_TEXTUAL_HEADER)); 02436 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name 02437 unsigned PrivateTextualHeaderAbbrev = Stream.EmitAbbrev(Abbrev); 02438 02439 Abbrev = new BitCodeAbbrev(); 02440 Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_LINK_LIBRARY)); 02441 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // IsFramework 02442 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name 02443 unsigned LinkLibraryAbbrev = Stream.EmitAbbrev(Abbrev); 02444 02445 Abbrev = new BitCodeAbbrev(); 02446 Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_CONFIG_MACRO)); 02447 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Macro name 02448 unsigned ConfigMacroAbbrev = Stream.EmitAbbrev(Abbrev); 02449 02450 Abbrev = new BitCodeAbbrev(); 02451 Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_CONFLICT)); 02452 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Other module 02453 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Message 02454 unsigned ConflictAbbrev = Stream.EmitAbbrev(Abbrev); 02455 02456 // Write the submodule metadata block. 02457 RecordData Record; 02458 Record.push_back(getNumberOfModules(WritingModule)); 02459 Record.push_back(FirstSubmoduleID - NUM_PREDEF_SUBMODULE_IDS); 02460 Stream.EmitRecord(SUBMODULE_METADATA, Record); 02461 02462 // Write all of the submodules. 02463 std::queue<Module *> Q; 02464 Q.push(WritingModule); 02465 while (!Q.empty()) { 02466 Module *Mod = Q.front(); 02467 Q.pop(); 02468 unsigned ID = getSubmoduleID(Mod); 02469 02470 // Emit the definition of the block. 02471 Record.clear(); 02472 Record.push_back(SUBMODULE_DEFINITION); 02473 Record.push_back(ID); 02474 if (Mod->Parent) { 02475 assert(SubmoduleIDs[Mod->Parent] && "Submodule parent not written?"); 02476 Record.push_back(SubmoduleIDs[Mod->Parent]); 02477 } else { 02478 Record.push_back(0); 02479 } 02480 Record.push_back(Mod->IsFramework); 02481 Record.push_back(Mod->IsExplicit); 02482 Record.push_back(Mod->IsSystem); 02483 Record.push_back(Mod->IsExternC); 02484 Record.push_back(Mod->InferSubmodules); 02485 Record.push_back(Mod->InferExplicitSubmodules); 02486 Record.push_back(Mod->InferExportWildcard); 02487 Record.push_back(Mod->ConfigMacrosExhaustive); 02488 Stream.EmitRecordWithBlob(DefinitionAbbrev, Record, Mod->Name); 02489 02490 // Emit the requirements. 02491 for (unsigned I = 0, N = Mod->Requirements.size(); I != N; ++I) { 02492 Record.clear(); 02493 Record.push_back(SUBMODULE_REQUIRES); 02494 Record.push_back(Mod->Requirements[I].second); 02495 Stream.EmitRecordWithBlob(RequiresAbbrev, Record, 02496 Mod->Requirements[I].first); 02497 } 02498 02499 // Emit the umbrella header, if there is one. 02500 if (const FileEntry *UmbrellaHeader = Mod->getUmbrellaHeader()) { 02501 Record.clear(); 02502 Record.push_back(SUBMODULE_UMBRELLA_HEADER); 02503 Stream.EmitRecordWithBlob(UmbrellaAbbrev, Record, 02504 UmbrellaHeader->getName()); 02505 } else if (const DirectoryEntry *UmbrellaDir = Mod->getUmbrellaDir()) { 02506 Record.clear(); 02507 Record.push_back(SUBMODULE_UMBRELLA_DIR); 02508 Stream.EmitRecordWithBlob(UmbrellaDirAbbrev, Record, 02509 UmbrellaDir->getName()); 02510 } 02511 02512 // Emit the headers. 02513 struct { 02514 unsigned Kind; 02515 unsigned Abbrev; 02516 ArrayRef<const FileEntry*> Headers; 02517 } HeaderLists[] = { 02518 {SUBMODULE_HEADER, HeaderAbbrev, Mod->NormalHeaders}, 02519 {SUBMODULE_TEXTUAL_HEADER, TextualHeaderAbbrev, Mod->TextualHeaders}, 02520 {SUBMODULE_PRIVATE_HEADER, PrivateHeaderAbbrev, Mod->PrivateHeaders}, 02521 {SUBMODULE_PRIVATE_TEXTUAL_HEADER, PrivateTextualHeaderAbbrev, 02522 Mod->PrivateTextualHeaders}, 02523 {SUBMODULE_EXCLUDED_HEADER, ExcludedHeaderAbbrev, Mod->ExcludedHeaders}, 02524 {SUBMODULE_TOPHEADER, TopHeaderAbbrev, 02525 Mod->getTopHeaders(PP->getFileManager())} 02526 }; 02527 for (auto &HL : HeaderLists) { 02528 Record.clear(); 02529 Record.push_back(HL.Kind); 02530 for (auto *H : HL.Headers) 02531 Stream.EmitRecordWithBlob(HL.Abbrev, Record, H->getName()); 02532 } 02533 02534 // Emit the imports. 02535 if (!Mod->Imports.empty()) { 02536 Record.clear(); 02537 for (unsigned I = 0, N = Mod->Imports.size(); I != N; ++I) { 02538 unsigned ImportedID = getSubmoduleID(Mod->Imports[I]); 02539 assert(ImportedID && "Unknown submodule!"); 02540 Record.push_back(ImportedID); 02541 } 02542 Stream.EmitRecord(SUBMODULE_IMPORTS, Record); 02543 } 02544 02545 // Emit the exports. 02546 if (!Mod->Exports.empty()) { 02547 Record.clear(); 02548 for (unsigned I = 0, N = Mod->Exports.size(); I != N; ++I) { 02549 if (Module *Exported = Mod->Exports[I].getPointer()) { 02550 unsigned ExportedID = SubmoduleIDs[Exported]; 02551 assert(ExportedID > 0 && "Unknown submodule ID?"); 02552 Record.push_back(ExportedID); 02553 } else { 02554 Record.push_back(0); 02555 } 02556 02557 Record.push_back(Mod->Exports[I].getInt()); 02558 } 02559 Stream.EmitRecord(SUBMODULE_EXPORTS, Record); 02560 } 02561 02562 //FIXME: How do we emit the 'use'd modules? They may not be submodules. 02563 // Might be unnecessary as use declarations are only used to build the 02564 // module itself. 02565 02566 // Emit the link libraries. 02567 for (unsigned I = 0, N = Mod->LinkLibraries.size(); I != N; ++I) { 02568 Record.clear(); 02569 Record.push_back(SUBMODULE_LINK_LIBRARY); 02570 Record.push_back(Mod->LinkLibraries[I].IsFramework); 02571 Stream.EmitRecordWithBlob(LinkLibraryAbbrev, Record, 02572 Mod->LinkLibraries[I].Library); 02573 } 02574 02575 // Emit the conflicts. 02576 for (unsigned I = 0, N = Mod->Conflicts.size(); I != N; ++I) { 02577 Record.clear(); 02578 Record.push_back(SUBMODULE_CONFLICT); 02579 unsigned OtherID = getSubmoduleID(Mod->Conflicts[I].Other); 02580 assert(OtherID && "Unknown submodule!"); 02581 Record.push_back(OtherID); 02582 Stream.EmitRecordWithBlob(ConflictAbbrev, Record, 02583 Mod->Conflicts[I].Message); 02584 } 02585 02586 // Emit the configuration macros. 02587 for (unsigned I = 0, N = Mod->ConfigMacros.size(); I != N; ++I) { 02588 Record.clear(); 02589 Record.push_back(SUBMODULE_CONFIG_MACRO); 02590 Stream.EmitRecordWithBlob(ConfigMacroAbbrev, Record, 02591 Mod->ConfigMacros[I]); 02592 } 02593 02594 // Queue up the submodules of this module. 02595 for (Module::submodule_iterator Sub = Mod->submodule_begin(), 02596 SubEnd = Mod->submodule_end(); 02597 Sub != SubEnd; ++Sub) 02598 Q.push(*Sub); 02599 } 02600 02601 Stream.ExitBlock(); 02602 02603 assert((NextSubmoduleID - FirstSubmoduleID 02604 == getNumberOfModules(WritingModule)) && "Wrong # of submodules"); 02605 } 02606 02607 serialization::SubmoduleID 02608 ASTWriter::inferSubmoduleIDFromLocation(SourceLocation Loc) { 02609 if (Loc.isInvalid() || !WritingModule) 02610 return 0; // No submodule 02611 02612 // Find the module that owns this location. 02613 ModuleMap &ModMap = PP->getHeaderSearchInfo().getModuleMap(); 02614 Module *OwningMod 02615 = ModMap.inferModuleFromLocation(FullSourceLoc(Loc,PP->getSourceManager())); 02616 if (!OwningMod) 02617 return 0; 02618 02619 // Check whether this submodule is part of our own module. 02620 if (WritingModule != OwningMod && !OwningMod->isSubModuleOf(WritingModule)) 02621 return 0; 02622 02623 return getSubmoduleID(OwningMod); 02624 } 02625 02626 void ASTWriter::WritePragmaDiagnosticMappings(const DiagnosticsEngine &Diag, 02627 bool isModule) { 02628 // Make sure set diagnostic pragmas don't affect the translation unit that 02629 // imports the module. 02630 // FIXME: Make diagnostic pragma sections work properly with modules. 02631 if (isModule) 02632 return; 02633 02634 llvm::SmallDenseMap<const DiagnosticsEngine::DiagState *, unsigned, 64> 02635 DiagStateIDMap; 02636 unsigned CurrID = 0; 02637 DiagStateIDMap[&Diag.DiagStates.front()] = ++CurrID; // the command-line one. 02638 RecordData Record; 02639 for (DiagnosticsEngine::DiagStatePointsTy::const_iterator 02640 I = Diag.DiagStatePoints.begin(), E = Diag.DiagStatePoints.end(); 02641 I != E; ++I) { 02642 const DiagnosticsEngine::DiagStatePoint &point = *I; 02643 if (point.Loc.isInvalid()) 02644 continue; 02645 02646 Record.push_back(point.Loc.getRawEncoding()); 02647 unsigned &DiagStateID = DiagStateIDMap[point.State]; 02648 Record.push_back(DiagStateID); 02649 02650 if (DiagStateID == 0) { 02651 DiagStateID = ++CurrID; 02652 for (DiagnosticsEngine::DiagState::const_iterator 02653 I = point.State->begin(), E = point.State->end(); I != E; ++I) { 02654 if (I->second.isPragma()) { 02655 Record.push_back(I->first); 02656 Record.push_back((unsigned)I->second.getSeverity()); 02657 } 02658 } 02659 Record.push_back(-1); // mark the end of the diag/map pairs for this 02660 // location. 02661 } 02662 } 02663 02664 if (!Record.empty()) 02665 Stream.EmitRecord(DIAG_PRAGMA_MAPPINGS, Record); 02666 } 02667 02668 void ASTWriter::WriteCXXBaseSpecifiersOffsets() { 02669 if (CXXBaseSpecifiersOffsets.empty()) 02670 return; 02671 02672 RecordData Record; 02673 02674 // Create a blob abbreviation for the C++ base specifiers offsets. 02675 using namespace llvm; 02676 02677 BitCodeAbbrev *Abbrev = new BitCodeAbbrev(); 02678 Abbrev->Add(BitCodeAbbrevOp(CXX_BASE_SPECIFIER_OFFSETS)); 02679 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // size 02680 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); 02681 unsigned BaseSpecifierOffsetAbbrev = Stream.EmitAbbrev(Abbrev); 02682 02683 // Write the base specifier offsets table. 02684 Record.clear(); 02685 Record.push_back(CXX_BASE_SPECIFIER_OFFSETS); 02686 Record.push_back(CXXBaseSpecifiersOffsets.size()); 02687 Stream.EmitRecordWithBlob(BaseSpecifierOffsetAbbrev, Record, 02688 data(CXXBaseSpecifiersOffsets)); 02689 } 02690 02691 //===----------------------------------------------------------------------===// 02692 // Type Serialization 02693 //===----------------------------------------------------------------------===// 02694 02695 /// \brief Write the representation of a type to the AST stream. 02696 void ASTWriter::WriteType(QualType T) { 02697 TypeIdx &Idx = TypeIdxs[T]; 02698 if (Idx.getIndex() == 0) // we haven't seen this type before. 02699 Idx = TypeIdx(NextTypeID++); 02700 02701 assert(Idx.getIndex() >= FirstTypeID && "Re-writing a type from a prior AST"); 02702 02703 // Record the offset for this type. 02704 unsigned Index = Idx.getIndex() - FirstTypeID; 02705 if (TypeOffsets.size() == Index) 02706 TypeOffsets.push_back(Stream.GetCurrentBitNo()); 02707 else if (TypeOffsets.size() < Index) { 02708 TypeOffsets.resize(Index + 1); 02709 TypeOffsets[Index] = Stream.GetCurrentBitNo(); 02710 } 02711 02712 RecordData Record; 02713 02714 // Emit the type's representation. 02715 ASTTypeWriter W(*this, Record); 02716 W.AbbrevToUse = 0; 02717 02718 if (T.hasLocalNonFastQualifiers()) { 02719 Qualifiers Qs = T.getLocalQualifiers(); 02720 AddTypeRef(T.getLocalUnqualifiedType(), Record); 02721 Record.push_back(Qs.getAsOpaqueValue()); 02722 W.Code = TYPE_EXT_QUAL; 02723 W.AbbrevToUse = TypeExtQualAbbrev; 02724 } else { 02725 switch (T->getTypeClass()) { 02726 // For all of the concrete, non-dependent types, call the 02727 // appropriate visitor function. 02728 #define TYPE(Class, Base) \ 02729 case Type::Class: W.Visit##Class##Type(cast<Class##Type>(T)); break; 02730 #define ABSTRACT_TYPE(Class, Base) 02731 #include "clang/AST/TypeNodes.def" 02732 } 02733 } 02734 02735 // Emit the serialized record. 02736 Stream.EmitRecord(W.Code, Record, W.AbbrevToUse); 02737 02738 // Flush any expressions that were written as part of this type. 02739 FlushStmts(); 02740 } 02741 02742 //===----------------------------------------------------------------------===// 02743 // Declaration Serialization 02744 //===----------------------------------------------------------------------===// 02745 02746 /// \brief Write the block containing all of the declaration IDs 02747 /// lexically declared within the given DeclContext. 02748 /// 02749 /// \returns the offset of the DECL_CONTEXT_LEXICAL block within the 02750 /// bistream, or 0 if no block was written. 02751 uint64_t ASTWriter::WriteDeclContextLexicalBlock(ASTContext &Context, 02752 DeclContext *DC) { 02753 if (DC->decls_empty()) 02754 return 0; 02755 02756 uint64_t Offset = Stream.GetCurrentBitNo(); 02757 RecordData Record; 02758 Record.push_back(DECL_CONTEXT_LEXICAL); 02759 SmallVector<KindDeclIDPair, 64> Decls; 02760 for (const auto *D : DC->decls()) 02761 Decls.push_back(std::make_pair(D->getKind(), GetDeclRef(D))); 02762 02763 ++NumLexicalDeclContexts; 02764 Stream.EmitRecordWithBlob(DeclContextLexicalAbbrev, Record, data(Decls)); 02765 return Offset; 02766 } 02767 02768 void ASTWriter::WriteTypeDeclOffsets() { 02769 using namespace llvm; 02770 RecordData Record; 02771 02772 // Write the type offsets array 02773 BitCodeAbbrev *Abbrev = new BitCodeAbbrev(); 02774 Abbrev->Add(BitCodeAbbrevOp(TYPE_OFFSET)); 02775 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // # of types 02776 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // base type index 02777 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // types block 02778 unsigned TypeOffsetAbbrev = Stream.EmitAbbrev(Abbrev); 02779 Record.clear(); 02780 Record.push_back(TYPE_OFFSET); 02781 Record.push_back(TypeOffsets.size()); 02782 Record.push_back(FirstTypeID - NUM_PREDEF_TYPE_IDS); 02783 Stream.EmitRecordWithBlob(TypeOffsetAbbrev, Record, data(TypeOffsets)); 02784 02785 // Write the declaration offsets array 02786 Abbrev = new BitCodeAbbrev(); 02787 Abbrev->Add(BitCodeAbbrevOp(DECL_OFFSET)); 02788 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // # of declarations 02789 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // base decl ID 02790 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // declarations block 02791 unsigned DeclOffsetAbbrev = Stream.EmitAbbrev(Abbrev); 02792 Record.clear(); 02793 Record.push_back(DECL_OFFSET); 02794 Record.push_back(DeclOffsets.size()); 02795 Record.push_back(FirstDeclID - NUM_PREDEF_DECL_IDS); 02796 Stream.EmitRecordWithBlob(DeclOffsetAbbrev, Record, data(DeclOffsets)); 02797 } 02798 02799 void ASTWriter::WriteFileDeclIDsMap() { 02800 using namespace llvm; 02801 RecordData Record; 02802 02803 // Join the vectors of DeclIDs from all files. 02804 SmallVector<DeclID, 256> FileSortedIDs; 02805 for (FileDeclIDsTy::iterator 02806 FI = FileDeclIDs.begin(), FE = FileDeclIDs.end(); FI != FE; ++FI) { 02807 DeclIDInFileInfo &Info = *FI->second; 02808 Info.FirstDeclIndex = FileSortedIDs.size(); 02809 for (LocDeclIDsTy::iterator 02810 DI = Info.DeclIDs.begin(), DE = Info.DeclIDs.end(); DI != DE; ++DI) 02811 FileSortedIDs.push_back(DI->second); 02812 } 02813 02814 BitCodeAbbrev *Abbrev = new BitCodeAbbrev(); 02815 Abbrev->Add(BitCodeAbbrevOp(FILE_SORTED_DECLS)); 02816 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); 02817 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); 02818 unsigned AbbrevCode = Stream.EmitAbbrev(Abbrev); 02819 Record.push_back(FILE_SORTED_DECLS); 02820 Record.push_back(FileSortedIDs.size()); 02821 Stream.EmitRecordWithBlob(AbbrevCode, Record, data(FileSortedIDs)); 02822 } 02823 02824 void ASTWriter::WriteComments() { 02825 Stream.EnterSubblock(COMMENTS_BLOCK_ID, 3); 02826 ArrayRef<RawComment *> RawComments = Context->Comments.getComments(); 02827 RecordData Record; 02828 for (ArrayRef<RawComment *>::iterator I = RawComments.begin(), 02829 E = RawComments.end(); 02830 I != E; ++I) { 02831 Record.clear(); 02832 AddSourceRange((*I)->getSourceRange(), Record); 02833 Record.push_back((*I)->getKind()); 02834 Record.push_back((*I)->isTrailingComment()); 02835 Record.push_back((*I)->isAlmostTrailingComment()); 02836 Stream.EmitRecord(COMMENTS_RAW_COMMENT, Record); 02837 } 02838 Stream.ExitBlock(); 02839 } 02840 02841 //===----------------------------------------------------------------------===// 02842 // Global Method Pool and Selector Serialization 02843 //===----------------------------------------------------------------------===// 02844 02845 namespace { 02846 // Trait used for the on-disk hash table used in the method pool. 02847 class ASTMethodPoolTrait { 02848 ASTWriter &Writer; 02849 02850 public: 02851 typedef Selector key_type; 02852 typedef key_type key_type_ref; 02853 02854 struct data_type { 02855 SelectorID ID; 02856 ObjCMethodList Instance, Factory; 02857 }; 02858 typedef const data_type& data_type_ref; 02859 02860 typedef unsigned hash_value_type; 02861 typedef unsigned offset_type; 02862 02863 explicit ASTMethodPoolTrait(ASTWriter &Writer) : Writer(Writer) { } 02864 02865 static hash_value_type ComputeHash(Selector Sel) { 02866 return serialization::ComputeHash(Sel); 02867 } 02868 02869 std::pair<unsigned,unsigned> 02870 EmitKeyDataLength(raw_ostream& Out, Selector Sel, 02871 data_type_ref Methods) { 02872 using namespace llvm::support; 02873 endian::Writer<little> LE(Out); 02874 unsigned KeyLen = 2 + (Sel.getNumArgs()? Sel.getNumArgs() * 4 : 4); 02875 LE.write<uint16_t>(KeyLen); 02876 unsigned DataLen = 4 + 2 + 2; // 2 bytes for each of the method counts 02877 for (const ObjCMethodList *Method = &Methods.Instance; Method; 02878 Method = Method->getNext()) 02879 if (Method->Method) 02880 DataLen += 4; 02881 for (const ObjCMethodList *Method = &Methods.Factory; Method; 02882 Method = Method->getNext()) 02883 if (Method->Method) 02884 DataLen += 4; 02885 LE.write<uint16_t>(DataLen); 02886 return std::make_pair(KeyLen, DataLen); 02887 } 02888 02889 void EmitKey(raw_ostream& Out, Selector Sel, unsigned) { 02890 using namespace llvm::support; 02891 endian::Writer<little> LE(Out); 02892 uint64_t Start = Out.tell(); 02893 assert((Start >> 32) == 0 && "Selector key offset too large"); 02894 Writer.SetSelectorOffset(Sel, Start); 02895 unsigned N = Sel.getNumArgs(); 02896 LE.write<uint16_t>(N); 02897 if (N == 0) 02898 N = 1; 02899 for (unsigned I = 0; I != N; ++I) 02900 LE.write<uint32_t>( 02901 Writer.getIdentifierRef(Sel.getIdentifierInfoForSlot(I))); 02902 } 02903 02904 void EmitData(raw_ostream& Out, key_type_ref, 02905 data_type_ref Methods, unsigned DataLen) { 02906 using namespace llvm::support; 02907 endian::Writer<little> LE(Out); 02908 uint64_t Start = Out.tell(); (void)Start; 02909 LE.write<uint32_t>(Methods.ID); 02910 unsigned NumInstanceMethods = 0; 02911 for (const ObjCMethodList *Method = &Methods.Instance; Method; 02912 Method = Method->getNext()) 02913 if (Method->Method) 02914 ++NumInstanceMethods; 02915 02916 unsigned NumFactoryMethods = 0; 02917 for (const ObjCMethodList *Method = &Methods.Factory; Method; 02918 Method = Method->getNext()) 02919 if (Method->Method) 02920 ++NumFactoryMethods; 02921 02922 unsigned InstanceBits = Methods.Instance.getBits(); 02923 assert(InstanceBits < 4); 02924 unsigned NumInstanceMethodsAndBits = 02925 (NumInstanceMethods << 2) | InstanceBits; 02926 unsigned FactoryBits = Methods.Factory.getBits(); 02927 assert(FactoryBits < 4); 02928 unsigned NumFactoryMethodsAndBits = (NumFactoryMethods << 2) | FactoryBits; 02929 LE.write<uint16_t>(NumInstanceMethodsAndBits); 02930 LE.write<uint16_t>(NumFactoryMethodsAndBits); 02931 for (const ObjCMethodList *Method = &Methods.Instance; Method; 02932 Method = Method->getNext()) 02933 if (Method->Method) 02934 LE.write<uint32_t>(Writer.getDeclID(Method->Method)); 02935 for (const ObjCMethodList *Method = &Methods.Factory; Method; 02936 Method = Method->getNext()) 02937 if (Method->Method) 02938 LE.write<uint32_t>(Writer.getDeclID(Method->Method)); 02939 02940 assert(Out.tell() - Start == DataLen && "Data length is wrong"); 02941 } 02942 }; 02943 } // end anonymous namespace 02944 02945 /// \brief Write ObjC data: selectors and the method pool. 02946 /// 02947 /// The method pool contains both instance and factory methods, stored 02948 /// in an on-disk hash table indexed by the selector. The hash table also 02949 /// contains an empty entry for every other selector known to Sema. 02950 void ASTWriter::WriteSelectors(Sema &SemaRef) { 02951 using namespace llvm; 02952 02953 // Do we have to do anything at all? 02954 if (SemaRef.MethodPool.empty() && SelectorIDs.empty()) 02955 return; 02956 unsigned NumTableEntries = 0; 02957 // Create and write out the blob that contains selectors and the method pool. 02958 { 02959 llvm::OnDiskChainedHashTableGenerator<ASTMethodPoolTrait> Generator; 02960 ASTMethodPoolTrait Trait(*this); 02961 02962 // Create the on-disk hash table representation. We walk through every 02963 // selector we've seen and look it up in the method pool. 02964 SelectorOffsets.resize(NextSelectorID - FirstSelectorID); 02965 for (llvm::DenseMap<Selector, SelectorID>::iterator 02966 I = SelectorIDs.begin(), E = SelectorIDs.end(); 02967 I != E; ++I) { 02968 Selector S = I->first; 02969 Sema::GlobalMethodPool::iterator F = SemaRef.MethodPool.find(S); 02970 ASTMethodPoolTrait::data_type Data = { 02971 I->second, 02972 ObjCMethodList(), 02973 ObjCMethodList() 02974 }; 02975 if (F != SemaRef.MethodPool.end()) { 02976 Data.Instance = F->second.first; 02977 Data.Factory = F->second.second; 02978 } 02979 // Only write this selector if it's not in an existing AST or something 02980 // changed. 02981 if (Chain && I->second < FirstSelectorID) { 02982 // Selector already exists. Did it change? 02983 bool changed = false; 02984 for (ObjCMethodList *M = &Data.Instance; !changed && M && M->Method; 02985 M = M->getNext()) { 02986 if (!M->Method->isFromASTFile()) 02987 changed = true; 02988 } 02989 for (ObjCMethodList *M = &Data.Factory; !changed && M && M->Method; 02990 M = M->getNext()) { 02991 if (!M->Method->isFromASTFile()) 02992 changed = true; 02993 } 02994 if (!changed) 02995 continue; 02996 } else if (Data.Instance.Method || Data.Factory.Method) { 02997 // A new method pool entry. 02998 ++NumTableEntries; 02999 } 03000 Generator.insert(S, Data, Trait); 03001 } 03002 03003 // Create the on-disk hash table in a buffer. 03004 SmallString<4096> MethodPool; 03005 uint32_t BucketOffset; 03006 { 03007 using namespace llvm::support; 03008 ASTMethodPoolTrait Trait(*this); 03009 llvm::raw_svector_ostream Out(MethodPool); 03010 // Make sure that no bucket is at offset 0 03011 endian::Writer<little>(Out).write<uint32_t>(0); 03012 BucketOffset = Generator.Emit(Out, Trait); 03013 } 03014 03015 // Create a blob abbreviation 03016 BitCodeAbbrev *Abbrev = new BitCodeAbbrev(); 03017 Abbrev->Add(BitCodeAbbrevOp(METHOD_POOL)); 03018 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); 03019 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); 03020 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); 03021 unsigned MethodPoolAbbrev = Stream.EmitAbbrev(Abbrev); 03022 03023 // Write the method pool 03024 RecordData Record; 03025 Record.push_back(METHOD_POOL); 03026 Record.push_back(BucketOffset); 03027 Record.push_back(NumTableEntries); 03028 Stream.EmitRecordWithBlob(MethodPoolAbbrev, Record, MethodPool.str()); 03029 03030 // Create a blob abbreviation for the selector table offsets. 03031 Abbrev = new BitCodeAbbrev(); 03032 Abbrev->Add(BitCodeAbbrevOp(SELECTOR_OFFSETS)); 03033 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // size 03034 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // first ID 03035 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); 03036 unsigned SelectorOffsetAbbrev = Stream.EmitAbbrev(Abbrev); 03037 03038 // Write the selector offsets table. 03039 Record.clear(); 03040 Record.push_back(SELECTOR_OFFSETS); 03041 Record.push_back(SelectorOffsets.size()); 03042 Record.push_back(FirstSelectorID - NUM_PREDEF_SELECTOR_IDS); 03043 Stream.EmitRecordWithBlob(SelectorOffsetAbbrev, Record, 03044 data(SelectorOffsets)); 03045 } 03046 } 03047 03048 /// \brief Write the selectors referenced in @selector expression into AST file. 03049 void ASTWriter::WriteReferencedSelectorsPool(Sema &SemaRef) { 03050 using namespace llvm; 03051 if (SemaRef.ReferencedSelectors.empty()) 03052 return; 03053 03054 RecordData Record; 03055 03056 // Note: this writes out all references even for a dependent AST. But it is 03057 // very tricky to fix, and given that @selector shouldn't really appear in 03058 // headers, probably not worth it. It's not a correctness issue. 03059 for (DenseMap<Selector, SourceLocation>::iterator S = 03060 SemaRef.ReferencedSelectors.begin(), 03061 E = SemaRef.ReferencedSelectors.end(); S != E; ++S) { 03062 Selector Sel = (*S).first; 03063 SourceLocation Loc = (*S).second; 03064 AddSelectorRef(Sel, Record); 03065 AddSourceLocation(Loc, Record); 03066 } 03067 Stream.EmitRecord(REFERENCED_SELECTOR_POOL, Record); 03068 } 03069 03070 //===----------------------------------------------------------------------===// 03071 // Identifier Table Serialization 03072 //===----------------------------------------------------------------------===// 03073 03074 namespace { 03075 class ASTIdentifierTableTrait { 03076 ASTWriter &Writer; 03077 Preprocessor &PP; 03078 IdentifierResolver &IdResolver; 03079 bool IsModule; 03080 03081 /// \brief Determines whether this is an "interesting" identifier 03082 /// that needs a full IdentifierInfo structure written into the hash 03083 /// table. 03084 bool isInterestingIdentifier(IdentifierInfo *II, MacroDirective *&Macro) { 03085 if (II->isPoisoned() || 03086 II->isExtensionToken() || 03087 II->getObjCOrBuiltinID() || 03088 II->hasRevertedTokenIDToIdentifier() || 03089 II->getFETokenInfo<void>()) 03090 return true; 03091 03092 return hadMacroDefinition(II, Macro); 03093 } 03094 03095 bool hadMacroDefinition(IdentifierInfo *II, MacroDirective *&Macro) { 03096 if (!II->hadMacroDefinition()) 03097 return false; 03098 03099 if (Macro || (Macro = PP.getMacroDirectiveHistory(II))) { 03100 if (!IsModule) 03101 return !shouldIgnoreMacro(Macro, IsModule, PP); 03102 03103 MacroState State; 03104 if (getFirstPublicSubmoduleMacro(Macro, State)) 03105 return true; 03106 } 03107 03108 return false; 03109 } 03110 03111 enum class SubmoduleMacroState { 03112 /// We've seen nothing about this macro. 03113 None, 03114 /// We've seen a public visibility directive. 03115 Public, 03116 /// We've either exported a macro for this module or found that the 03117 /// module's definition of this macro is private. 03118 Done 03119 }; 03120 typedef llvm::DenseMap<SubmoduleID, SubmoduleMacroState> MacroState; 03121 03122 MacroDirective * 03123 getFirstPublicSubmoduleMacro(MacroDirective *MD, MacroState &State) { 03124 if (MacroDirective *NextMD = getPublicSubmoduleMacro(MD, State)) 03125 return NextMD; 03126 return nullptr; 03127 } 03128 03129 MacroDirective * 03130 getNextPublicSubmoduleMacro(MacroDirective *MD, MacroState &State) { 03131 if (MacroDirective *NextMD = 03132 getPublicSubmoduleMacro(MD->getPrevious(), State)) 03133 return NextMD; 03134 return nullptr; 03135 } 03136 03137 /// \brief Traverses the macro directives history and returns the next 03138 /// public macro definition or undefinition that has not been found so far. 03139 /// 03140 /// A macro that is defined in submodule A and undefined in submodule B 03141 /// will still be considered as defined/exported from submodule A. 03142 MacroDirective *getPublicSubmoduleMacro(MacroDirective *MD, 03143 MacroState &State) { 03144 if (!MD) 03145 return nullptr; 03146 03147 Optional<bool> IsPublic; 03148 for (; MD; MD = MD->getPrevious()) { 03149 // Once we hit an ignored macro, we're done: the rest of the chain 03150 // will all be ignored macros. 03151 if (shouldIgnoreMacro(MD, IsModule, PP)) 03152 break; 03153 03154 // If this macro was imported, re-export it. 03155 if (MD->isImported()) 03156 return MD; 03157 03158 SubmoduleID ModID = getSubmoduleID(MD); 03159 auto &S = State[ModID]; 03160 assert(ModID && "found macro in no submodule"); 03161 03162 if (S == SubmoduleMacroState::Done) 03163 continue; 03164 03165 if (auto *VisMD = dyn_cast<VisibilityMacroDirective>(MD)) { 03166 // The latest visibility directive for a name in a submodule affects all 03167 // the directives that come before it. 03168 if (S == SubmoduleMacroState::None) 03169 S = VisMD->isPublic() ? SubmoduleMacroState::Public 03170 : SubmoduleMacroState::Done; 03171 } else { 03172 S = SubmoduleMacroState::Done; 03173 return MD; 03174 } 03175 } 03176 03177 return nullptr; 03178 } 03179 03180 ArrayRef<SubmoduleID> 03181 getOverriddenSubmodules(MacroDirective *MD, 03182 SmallVectorImpl<SubmoduleID> &ScratchSpace) { 03183 assert(!isa<VisibilityMacroDirective>(MD) && 03184 "only #define and #undef can override"); 03185 if (MD->isImported()) 03186 return MD->getOverriddenModules(); 03187 03188 ScratchSpace.clear(); 03189 SubmoduleID ModID = getSubmoduleID(MD); 03190 for (MD = MD->getPrevious(); MD; MD = MD->getPrevious()) { 03191 if (shouldIgnoreMacro(MD, IsModule, PP)) 03192 break; 03193 03194 // If this is a definition from a submodule import, that submodule's 03195 // definition is overridden by the definition or undefinition that we 03196 // started with. 03197 if (MD->isImported()) { 03198 if (auto *DefMD = dyn_cast<DefMacroDirective>(MD)) { 03199 SubmoduleID DefModuleID = DefMD->getInfo()->getOwningModuleID(); 03200 assert(DefModuleID && "imported macro has no owning module"); 03201 ScratchSpace.push_back(DefModuleID); 03202 } else if (auto *UndefMD = dyn_cast<UndefMacroDirective>(MD)) { 03203 // If we override a #undef, we override anything that #undef overrides. 03204 // We don't need to override it, since an active #undef doesn't affect 03205 // the meaning of a macro. 03206 auto Overrides = UndefMD->getOverriddenModules(); 03207 ScratchSpace.insert(ScratchSpace.end(), 03208 Overrides.begin(), Overrides.end()); 03209 } 03210 } 03211 03212 // Stop once we leave the original macro's submodule. 03213 // 03214 // Either this submodule #included another submodule of the same 03215 // module or it just happened to be built after the other module. 03216 // In the former case, we override the submodule's macro. 03217 // 03218 // FIXME: In the latter case, we shouldn't do so, but we can't tell 03219 // these cases apart. 03220 // 03221 // FIXME: We can leave this submodule and re-enter it if it #includes a 03222 // header within a different submodule of the same module. In such cases 03223 // the overrides list will be incomplete. 03224 SubmoduleID DirectiveModuleID = getSubmoduleID(MD); 03225 if (DirectiveModuleID != ModID) { 03226 if (DirectiveModuleID && !MD->isImported()) 03227 ScratchSpace.push_back(DirectiveModuleID); 03228 break; 03229 } 03230 } 03231 03232 std::sort(ScratchSpace.begin(), ScratchSpace.end()); 03233 ScratchSpace.erase(std::unique(ScratchSpace.begin(), ScratchSpace.end()), 03234 ScratchSpace.end()); 03235 return ScratchSpace; 03236 } 03237 03238 SubmoduleID getSubmoduleID(MacroDirective *MD) { 03239 return Writer.inferSubmoduleIDFromLocation(MD->getLocation()); 03240 } 03241 03242 public: 03243 typedef IdentifierInfo* key_type; 03244 typedef key_type key_type_ref; 03245 03246 typedef IdentID data_type; 03247 typedef data_type data_type_ref; 03248 03249 typedef unsigned hash_value_type; 03250 typedef unsigned offset_type; 03251 03252 ASTIdentifierTableTrait(ASTWriter &Writer, Preprocessor &PP, 03253 IdentifierResolver &IdResolver, bool IsModule) 03254 : Writer(Writer), PP(PP), IdResolver(IdResolver), IsModule(IsModule) { } 03255 03256 static hash_value_type ComputeHash(const IdentifierInfo* II) { 03257 return llvm::HashString(II->getName()); 03258 } 03259 03260 std::pair<unsigned,unsigned> 03261 EmitKeyDataLength(raw_ostream& Out, IdentifierInfo* II, IdentID ID) { 03262 unsigned KeyLen = II->getLength() + 1; 03263 unsigned DataLen = 4; // 4 bytes for the persistent ID << 1 03264 MacroDirective *Macro = nullptr; 03265 if (isInterestingIdentifier(II, Macro)) { 03266 DataLen += 2; // 2 bytes for builtin ID 03267 DataLen += 2; // 2 bytes for flags 03268 if (hadMacroDefinition(II, Macro)) { 03269 DataLen += 4; // MacroDirectives offset. 03270 if (IsModule) { 03271 MacroState State; 03272 SmallVector<SubmoduleID, 16> Scratch; 03273 for (MacroDirective *MD = getFirstPublicSubmoduleMacro(Macro, State); 03274 MD; MD = getNextPublicSubmoduleMacro(MD, State)) { 03275 DataLen += 4; // MacroInfo ID or ModuleID. 03276 if (unsigned NumOverrides = 03277 getOverriddenSubmodules(MD, Scratch).size()) 03278 DataLen += 4 * (1 + NumOverrides); 03279 } 03280 DataLen += 4; // 0 terminator. 03281 } 03282 } 03283 03284 for (IdentifierResolver::iterator D = IdResolver.begin(II), 03285 DEnd = IdResolver.end(); 03286 D != DEnd; ++D) 03287 DataLen += 4; 03288 } 03289 using namespace llvm::support; 03290 endian::Writer<little> LE(Out); 03291 03292 LE.write<uint16_t>(DataLen); 03293 // We emit the key length after the data length so that every 03294 // string is preceded by a 16-bit length. This matches the PTH 03295 // format for storing identifiers. 03296 LE.write<uint16_t>(KeyLen); 03297 return std::make_pair(KeyLen, DataLen); 03298 } 03299 03300 void EmitKey(raw_ostream& Out, const IdentifierInfo* II, 03301 unsigned KeyLen) { 03302 // Record the location of the key data. This is used when generating 03303 // the mapping from persistent IDs to strings. 03304 Writer.SetIdentifierOffset(II, Out.tell()); 03305 Out.write(II->getNameStart(), KeyLen); 03306 } 03307 03308 static void emitMacroOverrides(raw_ostream &Out, 03309 ArrayRef<SubmoduleID> Overridden) { 03310 if (!Overridden.empty()) { 03311 using namespace llvm::support; 03312 endian::Writer<little> LE(Out); 03313 LE.write<uint32_t>(Overridden.size() | 0x80000000U); 03314 for (unsigned I = 0, N = Overridden.size(); I != N; ++I) { 03315 assert(Overridden[I] && "zero module ID for override"); 03316 LE.write<uint32_t>(Overridden[I]); 03317 } 03318 } 03319 } 03320 03321 void EmitData(raw_ostream& Out, IdentifierInfo* II, 03322 IdentID ID, unsigned) { 03323 using namespace llvm::support; 03324 endian::Writer<little> LE(Out); 03325 MacroDirective *Macro = nullptr; 03326 if (!isInterestingIdentifier(II, Macro)) { 03327 LE.write<uint32_t>(ID << 1); 03328 return; 03329 } 03330 03331 LE.write<uint32_t>((ID << 1) | 0x01); 03332 uint32_t Bits = (uint32_t)II->getObjCOrBuiltinID(); 03333 assert((Bits & 0xffff) == Bits && "ObjCOrBuiltinID too big for ASTReader."); 03334 LE.write<uint16_t>(Bits); 03335 Bits = 0; 03336 bool HadMacroDefinition = hadMacroDefinition(II, Macro); 03337 Bits = (Bits << 1) | unsigned(HadMacroDefinition); 03338 Bits = (Bits << 1) | unsigned(IsModule); 03339 Bits = (Bits << 1) | unsigned(II->isExtensionToken()); 03340 Bits = (Bits << 1) | unsigned(II->isPoisoned()); 03341 Bits = (Bits << 1) | unsigned(II->hasRevertedTokenIDToIdentifier()); 03342 Bits = (Bits << 1) | unsigned(II->isCPlusPlusOperatorKeyword()); 03343 LE.write<uint16_t>(Bits); 03344 03345 if (HadMacroDefinition) { 03346 LE.write<uint32_t>(Writer.getMacroDirectivesOffset(II)); 03347 if (IsModule) { 03348 // Write the IDs of macros coming from different submodules. 03349 MacroState State; 03350 SmallVector<SubmoduleID, 16> Scratch; 03351 for (MacroDirective *MD = getFirstPublicSubmoduleMacro(Macro, State); 03352 MD; MD = getNextPublicSubmoduleMacro(MD, State)) { 03353 if (DefMacroDirective *DefMD = dyn_cast<DefMacroDirective>(MD)) { 03354 // FIXME: If this macro directive was created by #pragma pop_macros, 03355 // or if it was created implicitly by resolving conflicting macros, 03356 // it may be for a different submodule from the one in the MacroInfo 03357 // object. If so, we should write out its owning ModuleID. 03358 MacroID InfoID = Writer.getMacroID(DefMD->getInfo()); 03359 assert(InfoID); 03360 LE.write<uint32_t>(InfoID << 1); 03361 } else { 03362 auto *UndefMD = cast<UndefMacroDirective>(MD); 03363 SubmoduleID Mod = UndefMD->isImported() 03364 ? UndefMD->getOwningModuleID() 03365 : getSubmoduleID(UndefMD); 03366 LE.write<uint32_t>((Mod << 1) | 1); 03367 } 03368 emitMacroOverrides(Out, getOverriddenSubmodules(MD, Scratch)); 03369 } 03370 LE.write<uint32_t>(0xdeadbeef); 03371 } 03372 } 03373 03374 // Emit the declaration IDs in reverse order, because the 03375 // IdentifierResolver provides the declarations as they would be 03376 // visible (e.g., the function "stat" would come before the struct 03377 // "stat"), but the ASTReader adds declarations to the end of the list 03378 // (so we need to see the struct "status" before the function "status"). 03379 // Only emit declarations that aren't from a chained PCH, though. 03380 SmallVector<Decl *, 16> Decls(IdResolver.begin(II), 03381 IdResolver.end()); 03382 for (SmallVectorImpl<Decl *>::reverse_iterator D = Decls.rbegin(), 03383 DEnd = Decls.rend(); 03384 D != DEnd; ++D) 03385 LE.write<uint32_t>(Writer.getDeclID(getMostRecentLocalDecl(*D))); 03386 } 03387 03388 /// \brief Returns the most recent local decl or the given decl if there are 03389 /// no local ones. The given decl is assumed to be the most recent one. 03390 Decl *getMostRecentLocalDecl(Decl *Orig) { 03391 // The only way a "from AST file" decl would be more recent from a local one 03392 // is if it came from a module. 03393 if (!PP.getLangOpts().Modules) 03394 return Orig; 03395 03396 // Look for a local in the decl chain. 03397 for (Decl *D = Orig; D; D = D->getPreviousDecl()) { 03398 if (!D->isFromASTFile()) 03399 return D; 03400 // If we come up a decl from a (chained-)PCH stop since we won't find a 03401 // local one. 03402 if (D->getOwningModuleID() == 0) 03403 break; 03404 } 03405 03406 return Orig; 03407 } 03408 }; 03409 } // end anonymous namespace 03410 03411 /// \brief Write the identifier table into the AST file. 03412 /// 03413 /// The identifier table consists of a blob containing string data 03414 /// (the actual identifiers themselves) and a separate "offsets" index 03415 /// that maps identifier IDs to locations within the blob. 03416 void ASTWriter::WriteIdentifierTable(Preprocessor &PP, 03417 IdentifierResolver &IdResolver, 03418 bool IsModule) { 03419 using namespace llvm; 03420 03421 // Create and write out the blob that contains the identifier 03422 // strings. 03423 { 03424 llvm::OnDiskChainedHashTableGenerator<ASTIdentifierTableTrait> Generator; 03425 ASTIdentifierTableTrait Trait(*this, PP, IdResolver, IsModule); 03426 03427 // Look for any identifiers that were named while processing the 03428 // headers, but are otherwise not needed. We add these to the hash 03429 // table to enable checking of the predefines buffer in the case 03430 // where the user adds new macro definitions when building the AST 03431 // file. 03432 for (IdentifierTable::iterator ID = PP.getIdentifierTable().begin(), 03433 IDEnd = PP.getIdentifierTable().end(); 03434 ID != IDEnd; ++ID) 03435 getIdentifierRef(ID->second); 03436 03437 // Create the on-disk hash table representation. We only store offsets 03438 // for identifiers that appear here for the first time. 03439 IdentifierOffsets.resize(NextIdentID - FirstIdentID); 03440 for (llvm::DenseMap<const IdentifierInfo *, IdentID>::iterator 03441 ID = IdentifierIDs.begin(), IDEnd = IdentifierIDs.end(); 03442 ID != IDEnd; ++ID) { 03443 assert(ID->first && "NULL identifier in identifier table"); 03444 if (!Chain || !ID->first->isFromAST() || 03445 ID->first->hasChangedSinceDeserialization()) 03446 Generator.insert(const_cast<IdentifierInfo *>(ID->first), ID->second, 03447 Trait); 03448 } 03449 03450 // Create the on-disk hash table in a buffer. 03451 SmallString<4096> IdentifierTable; 03452 uint32_t BucketOffset; 03453 { 03454 using namespace llvm::support; 03455 ASTIdentifierTableTrait Trait(*this, PP, IdResolver, IsModule); 03456 llvm::raw_svector_ostream Out(IdentifierTable); 03457 // Make sure that no bucket is at offset 0 03458 endian::Writer<little>(Out).write<uint32_t>(0); 03459 BucketOffset = Generator.Emit(Out, Trait); 03460 } 03461 03462 // Create a blob abbreviation 03463 BitCodeAbbrev *Abbrev = new BitCodeAbbrev(); 03464 Abbrev->Add(BitCodeAbbrevOp(IDENTIFIER_TABLE)); 03465 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); 03466 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); 03467 unsigned IDTableAbbrev = Stream.EmitAbbrev(Abbrev); 03468 03469 // Write the identifier table 03470 RecordData Record; 03471 Record.push_back(IDENTIFIER_TABLE); 03472 Record.push_back(BucketOffset); 03473 Stream.EmitRecordWithBlob(IDTableAbbrev, Record, IdentifierTable.str()); 03474 } 03475 03476 // Write the offsets table for identifier IDs. 03477 BitCodeAbbrev *Abbrev = new BitCodeAbbrev(); 03478 Abbrev->Add(BitCodeAbbrevOp(IDENTIFIER_OFFSET)); 03479 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // # of identifiers 03480 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // first ID 03481 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); 03482 unsigned IdentifierOffsetAbbrev = Stream.EmitAbbrev(Abbrev); 03483 03484 #ifndef NDEBUG 03485 for (unsigned I = 0, N = IdentifierOffsets.size(); I != N; ++I) 03486 assert(IdentifierOffsets[I] && "Missing identifier offset?"); 03487 #endif 03488 03489 RecordData Record; 03490 Record.push_back(IDENTIFIER_OFFSET); 03491 Record.push_back(IdentifierOffsets.size()); 03492 Record.push_back(FirstIdentID - NUM_PREDEF_IDENT_IDS); 03493 Stream.EmitRecordWithBlob(IdentifierOffsetAbbrev, Record, 03494 data(IdentifierOffsets)); 03495 } 03496 03497 //===----------------------------------------------------------------------===// 03498 // DeclContext's Name Lookup Table Serialization 03499 //===----------------------------------------------------------------------===// 03500 03501 /// Determine the declaration that should be put into the name lookup table to 03502 /// represent the given declaration in this module. This is usually D itself, 03503 /// but if D was imported and merged into a local declaration, we want the most 03504 /// recent local declaration instead. The chosen declaration will be the most 03505 /// recent declaration in any module that imports this one. 03506 static NamedDecl *getDeclForLocalLookup(NamedDecl *D) { 03507 if (!D->isFromASTFile()) 03508 return D; 03509 03510 if (Decl *Redecl = D->getPreviousDecl()) { 03511 // For Redeclarable decls, a prior declaration might be local. 03512 for (; Redecl; Redecl = Redecl->getPreviousDecl()) 03513 if (!Redecl->isFromASTFile()) 03514 return cast<NamedDecl>(Redecl); 03515 } else if (Decl *First = D->getCanonicalDecl()) { 03516 // For Mergeable decls, the first decl might be local. 03517 if (!First->isFromASTFile()) 03518 return cast<NamedDecl>(First); 03519 } 03520 03521 // All declarations are imported. Our most recent declaration will also be 03522 // the most recent one in anyone who imports us. 03523 return D; 03524 } 03525 03526 namespace { 03527 // Trait used for the on-disk hash table used in the method pool. 03528 class ASTDeclContextNameLookupTrait { 03529 ASTWriter &Writer; 03530 03531 public: 03532 typedef DeclarationName key_type; 03533 typedef key_type key_type_ref; 03534 03535 typedef DeclContext::lookup_result data_type; 03536 typedef const data_type& data_type_ref; 03537 03538 typedef unsigned hash_value_type; 03539 typedef unsigned offset_type; 03540 03541 explicit ASTDeclContextNameLookupTrait(ASTWriter &Writer) : Writer(Writer) { } 03542 03543 hash_value_type ComputeHash(DeclarationName Name) { 03544 llvm::FoldingSetNodeID ID; 03545 ID.AddInteger(Name.getNameKind()); 03546 03547 switch (Name.getNameKind()) { 03548 case DeclarationName::Identifier: 03549 ID.AddString(Name.getAsIdentifierInfo()->getName()); 03550 break; 03551 case DeclarationName::ObjCZeroArgSelector: 03552 case DeclarationName::ObjCOneArgSelector: 03553 case DeclarationName::ObjCMultiArgSelector: 03554 ID.AddInteger(serialization::ComputeHash(Name.getObjCSelector())); 03555 break; 03556 case DeclarationName::CXXConstructorName: 03557 case DeclarationName::CXXDestructorName: 03558 case DeclarationName::CXXConversionFunctionName: 03559 break; 03560 case DeclarationName::CXXOperatorName: 03561 ID.AddInteger(Name.getCXXOverloadedOperator()); 03562 break; 03563 case DeclarationName::CXXLiteralOperatorName: 03564 ID.AddString(Name.getCXXLiteralIdentifier()->getName()); 03565 case DeclarationName::CXXUsingDirective: 03566 break; 03567 } 03568 03569 return ID.ComputeHash(); 03570 } 03571 03572 std::pair<unsigned,unsigned> 03573 EmitKeyDataLength(raw_ostream& Out, DeclarationName Name, 03574 data_type_ref Lookup) { 03575 using namespace llvm::support; 03576 endian::Writer<little> LE(Out); 03577 unsigned KeyLen = 1; 03578 switch (Name.getNameKind()) { 03579 case DeclarationName::Identifier: 03580 case DeclarationName::ObjCZeroArgSelector: 03581 case DeclarationName::ObjCOneArgSelector: 03582 case DeclarationName::ObjCMultiArgSelector: 03583 case DeclarationName::CXXLiteralOperatorName: 03584 KeyLen += 4; 03585 break; 03586 case DeclarationName::CXXOperatorName: 03587 KeyLen += 1; 03588 break; 03589 case DeclarationName::CXXConstructorName: 03590 case DeclarationName::CXXDestructorName: 03591 case DeclarationName::CXXConversionFunctionName: 03592 case DeclarationName::CXXUsingDirective: 03593 break; 03594 } 03595 LE.write<uint16_t>(KeyLen); 03596 03597 // 2 bytes for num of decls and 4 for each DeclID. 03598 unsigned DataLen = 2 + 4 * Lookup.size(); 03599 LE.write<uint16_t>(DataLen); 03600 03601 return std::make_pair(KeyLen, DataLen); 03602 } 03603 03604 void EmitKey(raw_ostream& Out, DeclarationName Name, unsigned) { 03605 using namespace llvm::support; 03606 endian::Writer<little> LE(Out); 03607 LE.write<uint8_t>(Name.getNameKind()); 03608 switch (Name.getNameKind()) { 03609 case DeclarationName::Identifier: 03610 LE.write<uint32_t>(Writer.getIdentifierRef(Name.getAsIdentifierInfo())); 03611 return; 03612 case DeclarationName::ObjCZeroArgSelector: 03613 case DeclarationName::ObjCOneArgSelector: 03614 case DeclarationName::ObjCMultiArgSelector: 03615 LE.write<uint32_t>(Writer.getSelectorRef(Name.getObjCSelector())); 03616 return; 03617 case DeclarationName::CXXOperatorName: 03618 assert(Name.getCXXOverloadedOperator() < NUM_OVERLOADED_OPERATORS && 03619 "Invalid operator?"); 03620 LE.write<uint8_t>(Name.getCXXOverloadedOperator()); 03621 return; 03622 case DeclarationName::CXXLiteralOperatorName: 03623 LE.write<uint32_t>(Writer.getIdentifierRef(Name.getCXXLiteralIdentifier())); 03624 return; 03625 case DeclarationName::CXXConstructorName: 03626 case DeclarationName::CXXDestructorName: 03627 case DeclarationName::CXXConversionFunctionName: 03628 case DeclarationName::CXXUsingDirective: 03629 return; 03630 } 03631 03632 llvm_unreachable("Invalid name kind?"); 03633 } 03634 03635 void EmitData(raw_ostream& Out, key_type_ref, 03636 data_type Lookup, unsigned DataLen) { 03637 using namespace llvm::support; 03638 endian::Writer<little> LE(Out); 03639 uint64_t Start = Out.tell(); (void)Start; 03640 LE.write<uint16_t>(Lookup.size()); 03641 for (DeclContext::lookup_iterator I = Lookup.begin(), E = Lookup.end(); 03642 I != E; ++I) 03643 LE.write<uint32_t>(Writer.GetDeclRef(getDeclForLocalLookup(*I))); 03644 03645 assert(Out.tell() - Start == DataLen && "Data length is wrong"); 03646 } 03647 }; 03648 } // end anonymous namespace 03649 03650 template<typename Visitor> 03651 static void visitLocalLookupResults(const DeclContext *ConstDC, 03652 bool NeedToReconcileExternalVisibleStorage, 03653 Visitor AddLookupResult) { 03654 // FIXME: We need to build the lookups table, which is logically const. 03655 DeclContext *DC = const_cast<DeclContext*>(ConstDC); 03656 assert(DC == DC->getPrimaryContext() && "only primary DC has lookup table"); 03657 03658 SmallVector<DeclarationName, 16> ExternalNames; 03659 for (auto &Lookup : *DC->buildLookup()) { 03660 if (Lookup.second.hasExternalDecls() || 03661 NeedToReconcileExternalVisibleStorage) { 03662 // We don't know for sure what declarations are found by this name, 03663 // because the external source might have a different set from the set 03664 // that are in the lookup map, and we can't update it now without 03665 // risking invalidating our lookup iterator. So add it to a queue to 03666 // deal with later. 03667 ExternalNames.push_back(Lookup.first); 03668 continue; 03669 } 03670 03671 AddLookupResult(Lookup.first, Lookup.second.getLookupResult()); 03672 } 03673 03674 // Add the names we needed to defer. Note, this shouldn't add any new decls 03675 // to the list we need to serialize: any new declarations we find here should 03676 // be imported from an external source. 03677 // FIXME: What if the external source isn't an ASTReader? 03678 for (const auto &Name : ExternalNames) 03679 AddLookupResult(Name, DC->lookup(Name)); 03680 } 03681 03682 void ASTWriter::AddUpdatedDeclContext(const DeclContext *DC) { 03683 if (UpdatedDeclContexts.insert(DC) && WritingAST) { 03684 // Ensure we emit all the visible declarations. 03685 visitLocalLookupResults(DC, DC->NeedToReconcileExternalVisibleStorage, 03686 [&](DeclarationName Name, 03687 DeclContext::lookup_const_result Result) { 03688 for (auto *Decl : Result) 03689 GetDeclRef(getDeclForLocalLookup(Decl)); 03690 }); 03691 } 03692 } 03693 03694 uint32_t 03695 ASTWriter::GenerateNameLookupTable(const DeclContext *DC, 03696 llvm::SmallVectorImpl<char> &LookupTable) { 03697 assert(!DC->LookupPtr.getInt() && "must call buildLookups first"); 03698 03699 llvm::OnDiskChainedHashTableGenerator<ASTDeclContextNameLookupTrait> 03700 Generator; 03701 ASTDeclContextNameLookupTrait Trait(*this); 03702 03703 // Create the on-disk hash table representation. 03704 DeclarationName ConstructorName; 03705 DeclarationName ConversionName; 03706 SmallVector<NamedDecl *, 8> ConstructorDecls; 03707 SmallVector<NamedDecl *, 4> ConversionDecls; 03708 03709 visitLocalLookupResults(DC, DC->NeedToReconcileExternalVisibleStorage, 03710 [&](DeclarationName Name, 03711 DeclContext::lookup_result Result) { 03712 if (Result.empty()) 03713 return; 03714 03715 // Different DeclarationName values of certain kinds are mapped to 03716 // identical serialized keys, because we don't want to use type 03717 // identifiers in the keys (since type ids are local to the module). 03718 switch (Name.getNameKind()) { 03719 case DeclarationName::CXXConstructorName: 03720 // There may be different CXXConstructorName DeclarationName values 03721 // in a DeclContext because a UsingDecl that inherits constructors 03722 // has the DeclarationName of the inherited constructors. 03723 if (!ConstructorName) 03724 ConstructorName = Name; 03725 ConstructorDecls.append(Result.begin(), Result.end()); 03726 return; 03727 03728 case DeclarationName::CXXConversionFunctionName: 03729 if (!ConversionName) 03730 ConversionName = Name; 03731 ConversionDecls.append(Result.begin(), Result.end()); 03732 return; 03733 03734 default: 03735 break; 03736 } 03737 03738 Generator.insert(Name, Result, Trait); 03739 }); 03740 03741 // Add the constructors. 03742 if (!ConstructorDecls.empty()) { 03743 Generator.insert(ConstructorName, 03744 DeclContext::lookup_result(ConstructorDecls.begin(), 03745 ConstructorDecls.end()), 03746 Trait); 03747 } 03748 03749 // Add the conversion functions. 03750 if (!ConversionDecls.empty()) { 03751 Generator.insert(ConversionName, 03752 DeclContext::lookup_result(ConversionDecls.begin(), 03753 ConversionDecls.end()), 03754 Trait); 03755 } 03756 03757 // Create the on-disk hash table in a buffer. 03758 llvm::raw_svector_ostream Out(LookupTable); 03759 // Make sure that no bucket is at offset 0 03760 using namespace llvm::support; 03761 endian::Writer<little>(Out).write<uint32_t>(0); 03762 return Generator.Emit(Out, Trait); 03763 } 03764 03765 /// \brief Write the block containing all of the declaration IDs 03766 /// visible from the given DeclContext. 03767 /// 03768 /// \returns the offset of the DECL_CONTEXT_VISIBLE block within the 03769 /// bitstream, or 0 if no block was written. 03770 uint64_t ASTWriter::WriteDeclContextVisibleBlock(ASTContext &Context, 03771 DeclContext *DC) { 03772 if (DC->getPrimaryContext() != DC) 03773 return 0; 03774 03775 // Since there is no name lookup into functions or methods, don't bother to 03776 // build a visible-declarations table for these entities. 03777 if (DC->isFunctionOrMethod()) 03778 return 0; 03779 03780 // If not in C++, we perform name lookup for the translation unit via the 03781 // IdentifierInfo chains, don't bother to build a visible-declarations table. 03782 if (DC->isTranslationUnit() && !Context.getLangOpts().CPlusPlus) 03783 return 0; 03784 03785 // Serialize the contents of the mapping used for lookup. Note that, 03786 // although we have two very different code paths, the serialized 03787 // representation is the same for both cases: a declaration name, 03788 // followed by a size, followed by references to the visible 03789 // declarations that have that name. 03790 uint64_t Offset = Stream.GetCurrentBitNo(); 03791 StoredDeclsMap *Map = DC->buildLookup(); 03792 if (!Map || Map->empty()) 03793 return 0; 03794 03795 // Create the on-disk hash table in a buffer. 03796 SmallString<4096> LookupTable; 03797 uint32_t BucketOffset = GenerateNameLookupTable(DC, LookupTable); 03798 03799 // Write the lookup table 03800 RecordData Record; 03801 Record.push_back(DECL_CONTEXT_VISIBLE); 03802 Record.push_back(BucketOffset); 03803 Stream.EmitRecordWithBlob(DeclContextVisibleLookupAbbrev, Record, 03804 LookupTable.str()); 03805 ++NumVisibleDeclContexts; 03806 return Offset; 03807 } 03808 03809 /// \brief Write an UPDATE_VISIBLE block for the given context. 03810 /// 03811 /// UPDATE_VISIBLE blocks contain the declarations that are added to an existing 03812 /// DeclContext in a dependent AST file. As such, they only exist for the TU 03813 /// (in C++), for namespaces, and for classes with forward-declared unscoped 03814 /// enumeration members (in C++11). 03815 void ASTWriter::WriteDeclContextVisibleUpdate(const DeclContext *DC) { 03816 StoredDeclsMap *Map = DC->getLookupPtr(); 03817 if (!Map || Map->empty()) 03818 return; 03819 03820 // Create the on-disk hash table in a buffer. 03821 SmallString<4096> LookupTable; 03822 uint32_t BucketOffset = GenerateNameLookupTable(DC, LookupTable); 03823 03824 // Write the lookup table 03825 RecordData Record; 03826 Record.push_back(UPDATE_VISIBLE); 03827 Record.push_back(getDeclID(cast<Decl>(DC))); 03828 Record.push_back(BucketOffset); 03829 Stream.EmitRecordWithBlob(UpdateVisibleAbbrev, Record, LookupTable.str()); 03830 } 03831 03832 /// \brief Write an FP_PRAGMA_OPTIONS block for the given FPOptions. 03833 void ASTWriter::WriteFPPragmaOptions(const FPOptions &Opts) { 03834 RecordData Record; 03835 Record.push_back(Opts.fp_contract); 03836 Stream.EmitRecord(FP_PRAGMA_OPTIONS, Record); 03837 } 03838 03839 /// \brief Write an OPENCL_EXTENSIONS block for the given OpenCLOptions. 03840 void ASTWriter::WriteOpenCLExtensions(Sema &SemaRef) { 03841 if (!SemaRef.Context.getLangOpts().OpenCL) 03842 return; 03843 03844 const OpenCLOptions &Opts = SemaRef.getOpenCLOptions(); 03845 RecordData Record; 03846 #define OPENCLEXT(nm) Record.push_back(Opts.nm); 03847 #include "clang/Basic/OpenCLExtensions.def" 03848 Stream.EmitRecord(OPENCL_EXTENSIONS, Record); 03849 } 03850 03851 void ASTWriter::WriteRedeclarations() { 03852 RecordData LocalRedeclChains; 03853 SmallVector<serialization::LocalRedeclarationsInfo, 2> LocalRedeclsMap; 03854 03855 for (unsigned I = 0, N = Redeclarations.size(); I != N; ++I) { 03856 Decl *First = Redeclarations[I]; 03857 assert(First->isFirstDecl() && "Not the first declaration?"); 03858 03859 Decl *MostRecent = First->getMostRecentDecl(); 03860 03861 // If we only have a single declaration, there is no point in storing 03862 // a redeclaration chain. 03863 if (First == MostRecent) 03864 continue; 03865 03866 unsigned Offset = LocalRedeclChains.size(); 03867 unsigned Size = 0; 03868 LocalRedeclChains.push_back(0); // Placeholder for the size. 03869 03870 // Collect the set of local redeclarations of this declaration. 03871 for (Decl *Prev = MostRecent; Prev != First; 03872 Prev = Prev->getPreviousDecl()) { 03873 if (!Prev->isFromASTFile()) { 03874 AddDeclRef(Prev, LocalRedeclChains); 03875 ++Size; 03876 } 03877 } 03878 03879 if (!First->isFromASTFile() && Chain) { 03880 Decl *FirstFromAST = MostRecent; 03881 for (Decl *Prev = MostRecent; Prev; Prev = Prev->getPreviousDecl()) { 03882 if (Prev->isFromASTFile()) 03883 FirstFromAST = Prev; 03884 } 03885 03886 // FIXME: Do we need to do this for the first declaration from each 03887 // redeclaration chain that was merged into this one? 03888 Chain->MergedDecls[FirstFromAST].push_back(getDeclID(First)); 03889 } 03890 03891 LocalRedeclChains[Offset] = Size; 03892 03893 // Reverse the set of local redeclarations, so that we store them in 03894 // order (since we found them in reverse order). 03895 std::reverse(LocalRedeclChains.end() - Size, LocalRedeclChains.end()); 03896 03897 // Add the mapping from the first ID from the AST to the set of local 03898 // declarations. 03899 LocalRedeclarationsInfo Info = { getDeclID(First), Offset }; 03900 LocalRedeclsMap.push_back(Info); 03901 03902 assert(N == Redeclarations.size() && 03903 "Deserialized a declaration we shouldn't have"); 03904 } 03905 03906 if (LocalRedeclChains.empty()) 03907 return; 03908 03909 // Sort the local redeclarations map by the first declaration ID, 03910 // since the reader will be performing binary searches on this information. 03911 llvm::array_pod_sort(LocalRedeclsMap.begin(), LocalRedeclsMap.end()); 03912 03913 // Emit the local redeclarations map. 03914 using namespace llvm; 03915 llvm::BitCodeAbbrev *Abbrev = new BitCodeAbbrev(); 03916 Abbrev->Add(BitCodeAbbrevOp(LOCAL_REDECLARATIONS_MAP)); 03917 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // # of entries 03918 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); 03919 unsigned AbbrevID = Stream.EmitAbbrev(Abbrev); 03920 03921 RecordData Record; 03922 Record.push_back(LOCAL_REDECLARATIONS_MAP); 03923 Record.push_back(LocalRedeclsMap.size()); 03924 Stream.EmitRecordWithBlob(AbbrevID, Record, 03925 reinterpret_cast<char*>(LocalRedeclsMap.data()), 03926 LocalRedeclsMap.size() * sizeof(LocalRedeclarationsInfo)); 03927 03928 // Emit the redeclaration chains. 03929 Stream.EmitRecord(LOCAL_REDECLARATIONS, LocalRedeclChains); 03930 } 03931 03932 void ASTWriter::WriteObjCCategories() { 03933 SmallVector<ObjCCategoriesInfo, 2> CategoriesMap; 03934 RecordData Categories; 03935 03936 for (unsigned I = 0, N = ObjCClassesWithCategories.size(); I != N; ++I) { 03937 unsigned Size = 0; 03938 unsigned StartIndex = Categories.size(); 03939 03940 ObjCInterfaceDecl *Class = ObjCClassesWithCategories[I]; 03941 03942 // Allocate space for the size. 03943 Categories.push_back(0); 03944 03945 // Add the categories. 03946 for (ObjCInterfaceDecl::known_categories_iterator 03947 Cat = Class->known_categories_begin(), 03948 CatEnd = Class->known_categories_end(); 03949 Cat != CatEnd; ++Cat, ++Size) { 03950 assert(getDeclID(*Cat) != 0 && "Bogus category"); 03951 AddDeclRef(*Cat, Categories); 03952 } 03953 03954 // Update the size. 03955 Categories[StartIndex] = Size; 03956 03957 // Record this interface -> category map. 03958 ObjCCategoriesInfo CatInfo = { getDeclID(Class), StartIndex }; 03959 CategoriesMap.push_back(CatInfo); 03960 } 03961 03962 // Sort the categories map by the definition ID, since the reader will be 03963 // performing binary searches on this information. 03964 llvm::array_pod_sort(CategoriesMap.begin(), CategoriesMap.end()); 03965 03966 // Emit the categories map. 03967 using namespace llvm; 03968 llvm::BitCodeAbbrev *Abbrev = new BitCodeAbbrev(); 03969 Abbrev->Add(BitCodeAbbrevOp(OBJC_CATEGORIES_MAP)); 03970 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // # of entries 03971 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); 03972 unsigned AbbrevID = Stream.EmitAbbrev(Abbrev); 03973 03974 RecordData Record; 03975 Record.push_back(OBJC_CATEGORIES_MAP); 03976 Record.push_back(CategoriesMap.size()); 03977 Stream.EmitRecordWithBlob(AbbrevID, Record, 03978 reinterpret_cast<char*>(CategoriesMap.data()), 03979 CategoriesMap.size() * sizeof(ObjCCategoriesInfo)); 03980 03981 // Emit the category lists. 03982 Stream.EmitRecord(OBJC_CATEGORIES, Categories); 03983 } 03984 03985 void ASTWriter::WriteMergedDecls() { 03986 if (!Chain || Chain->MergedDecls.empty()) 03987 return; 03988 03989 RecordData Record; 03990 for (ASTReader::MergedDeclsMap::iterator I = Chain->MergedDecls.begin(), 03991 IEnd = Chain->MergedDecls.end(); 03992 I != IEnd; ++I) { 03993 DeclID CanonID = I->first->isFromASTFile()? I->first->getGlobalID() 03994 : GetDeclRef(I->first); 03995 assert(CanonID && "Merged declaration not known?"); 03996 03997 Record.push_back(CanonID); 03998 Record.push_back(I->second.size()); 03999 Record.append(I->second.begin(), I->second.end()); 04000 } 04001 Stream.EmitRecord(MERGED_DECLARATIONS, Record); 04002 } 04003 04004 void ASTWriter::WriteLateParsedTemplates(Sema &SemaRef) { 04005 Sema::LateParsedTemplateMapT &LPTMap = SemaRef.LateParsedTemplateMap; 04006 04007 if (LPTMap.empty()) 04008 return; 04009 04010 RecordData Record; 04011 for (Sema::LateParsedTemplateMapT::iterator It = LPTMap.begin(), 04012 ItEnd = LPTMap.end(); 04013 It != ItEnd; ++It) { 04014 LateParsedTemplate *LPT = It->second; 04015 AddDeclRef(It->first, Record); 04016 AddDeclRef(LPT->D, Record); 04017 Record.push_back(LPT->Toks.size()); 04018 04019 for (CachedTokens::iterator TokIt = LPT->Toks.begin(), 04020 TokEnd = LPT->Toks.end(); 04021 TokIt != TokEnd; ++TokIt) { 04022 AddToken(*TokIt, Record); 04023 } 04024 } 04025 Stream.EmitRecord(LATE_PARSED_TEMPLATE, Record); 04026 } 04027 04028 /// \brief Write the state of 'pragma clang optimize' at the end of the module. 04029 void ASTWriter::WriteOptimizePragmaOptions(Sema &SemaRef) { 04030 RecordData Record; 04031 SourceLocation PragmaLoc = SemaRef.getOptimizeOffPragmaLocation(); 04032 AddSourceLocation(PragmaLoc, Record); 04033 Stream.EmitRecord(OPTIMIZE_PRAGMA_OPTIONS, Record); 04034 } 04035 04036 //===----------------------------------------------------------------------===// 04037 // General Serialization Routines 04038 //===----------------------------------------------------------------------===// 04039 04040 /// \brief Write a record containing the given attributes. 04041 void ASTWriter::WriteAttributes(ArrayRef<const Attr*> Attrs, 04042 RecordDataImpl &Record) { 04043 Record.push_back(Attrs.size()); 04044 for (ArrayRef<const Attr *>::iterator i = Attrs.begin(), 04045 e = Attrs.end(); i != e; ++i){ 04046 const Attr *A = *i; 04047 Record.push_back(A->getKind()); // FIXME: stable encoding, target attrs 04048 AddSourceRange(A->getRange(), Record); 04049 04050 #include "clang/Serialization/AttrPCHWrite.inc" 04051 04052 } 04053 } 04054 04055 void ASTWriter::AddToken(const Token &Tok, RecordDataImpl &Record) { 04056 AddSourceLocation(Tok.getLocation(), Record); 04057 Record.push_back(Tok.getLength()); 04058 04059 // FIXME: When reading literal tokens, reconstruct the literal pointer 04060 // if it is needed. 04061 AddIdentifierRef(Tok.getIdentifierInfo(), Record); 04062 // FIXME: Should translate token kind to a stable encoding. 04063 Record.push_back(Tok.getKind()); 04064 // FIXME: Should translate token flags to a stable encoding. 04065 Record.push_back(Tok.getFlags()); 04066 } 04067 04068 void ASTWriter::AddString(StringRef Str, RecordDataImpl &Record) { 04069 Record.push_back(Str.size()); 04070 Record.insert(Record.end(), Str.begin(), Str.end()); 04071 } 04072 04073 void ASTWriter::AddVersionTuple(const VersionTuple &Version, 04074 RecordDataImpl &Record) { 04075 Record.push_back(Version.getMajor()); 04076 if (Optional<unsigned> Minor = Version.getMinor()) 04077 Record.push_back(*Minor + 1); 04078 else 04079 Record.push_back(0); 04080 if (Optional<unsigned> Subminor = Version.getSubminor()) 04081 Record.push_back(*Subminor + 1); 04082 else 04083 Record.push_back(0); 04084 } 04085 04086 /// \brief Note that the identifier II occurs at the given offset 04087 /// within the identifier table. 04088 void ASTWriter::SetIdentifierOffset(const IdentifierInfo *II, uint32_t Offset) { 04089 IdentID ID = IdentifierIDs[II]; 04090 // Only store offsets new to this AST file. Other identifier names are looked 04091 // up earlier in the chain and thus don't need an offset. 04092 if (ID >= FirstIdentID) 04093 IdentifierOffsets[ID - FirstIdentID] = Offset; 04094 } 04095 04096 /// \brief Note that the selector Sel occurs at the given offset 04097 /// within the method pool/selector table. 04098 void ASTWriter::SetSelectorOffset(Selector Sel, uint32_t Offset) { 04099 unsigned ID = SelectorIDs[Sel]; 04100 assert(ID && "Unknown selector"); 04101 // Don't record offsets for selectors that are also available in a different 04102 // file. 04103 if (ID < FirstSelectorID) 04104 return; 04105 SelectorOffsets[ID - FirstSelectorID] = Offset; 04106 } 04107 04108 ASTWriter::ASTWriter(llvm::BitstreamWriter &Stream) 04109 : Stream(Stream), Context(nullptr), PP(nullptr), Chain(nullptr), 04110 WritingModule(nullptr), WritingAST(false), 04111 DoneWritingDeclsAndTypes(false), ASTHasCompilerErrors(false), 04112 FirstDeclID(NUM_PREDEF_DECL_IDS), NextDeclID(FirstDeclID), 04113 FirstTypeID(NUM_PREDEF_TYPE_IDS), NextTypeID(FirstTypeID), 04114 FirstIdentID(NUM_PREDEF_IDENT_IDS), NextIdentID(FirstIdentID), 04115 FirstMacroID(NUM_PREDEF_MACRO_IDS), NextMacroID(FirstMacroID), 04116 FirstSubmoduleID(NUM_PREDEF_SUBMODULE_IDS), 04117 NextSubmoduleID(FirstSubmoduleID), 04118 FirstSelectorID(NUM_PREDEF_SELECTOR_IDS), NextSelectorID(FirstSelectorID), 04119 CollectedStmts(&StmtsToEmit), NumStatements(0), NumMacros(0), 04120 NumLexicalDeclContexts(0), NumVisibleDeclContexts(0), 04121 NextCXXBaseSpecifiersID(1), TypeExtQualAbbrev(0), 04122 TypeFunctionProtoAbbrev(0), DeclParmVarAbbrev(0), 04123 DeclContextLexicalAbbrev(0), DeclContextVisibleLookupAbbrev(0), 04124 UpdateVisibleAbbrev(0), DeclRecordAbbrev(0), DeclTypedefAbbrev(0), 04125 DeclVarAbbrev(0), DeclFieldAbbrev(0), DeclEnumAbbrev(0), 04126 DeclObjCIvarAbbrev(0), DeclCXXMethodAbbrev(0), DeclRefExprAbbrev(0), 04127 CharacterLiteralAbbrev(0), IntegerLiteralAbbrev(0), 04128 ExprImplicitCastAbbrev(0) {} 04129 04130 ASTWriter::~ASTWriter() { 04131 llvm::DeleteContainerSeconds(FileDeclIDs); 04132 } 04133 04134 void ASTWriter::WriteAST(Sema &SemaRef, 04135 const std::string &OutputFile, 04136 Module *WritingModule, StringRef isysroot, 04137 bool hasErrors) { 04138 WritingAST = true; 04139 04140 ASTHasCompilerErrors = hasErrors; 04141 04142 // Emit the file header. 04143 Stream.Emit((unsigned)'C', 8); 04144 Stream.Emit((unsigned)'P', 8); 04145 Stream.Emit((unsigned)'C', 8); 04146 Stream.Emit((unsigned)'H', 8); 04147 04148 WriteBlockInfoBlock(); 04149 04150 Context = &SemaRef.Context; 04151 PP = &SemaRef.PP; 04152 this->WritingModule = WritingModule; 04153 WriteASTCore(SemaRef, isysroot, OutputFile, WritingModule); 04154 Context = nullptr; 04155 PP = nullptr; 04156 this->WritingModule = nullptr; 04157 04158 WritingAST = false; 04159 } 04160 04161 template<typename Vector> 04162 static void AddLazyVectorDecls(ASTWriter &Writer, Vector &Vec, 04163 ASTWriter::RecordData &Record) { 04164 for (typename Vector::iterator I = Vec.begin(nullptr, true), E = Vec.end(); 04165 I != E; ++I) { 04166 Writer.AddDeclRef(*I, Record); 04167 } 04168 } 04169 04170 void ASTWriter::WriteASTCore(Sema &SemaRef, 04171 StringRef isysroot, 04172 const std::string &OutputFile, 04173 Module *WritingModule) { 04174 using namespace llvm; 04175 04176 bool isModule = WritingModule != nullptr; 04177 04178 // Make sure that the AST reader knows to finalize itself. 04179 if (Chain) 04180 Chain->finalizeForWriting(); 04181 04182 ASTContext &Context = SemaRef.Context; 04183 Preprocessor &PP = SemaRef.PP; 04184 04185 // Set up predefined declaration IDs. 04186 DeclIDs[Context.getTranslationUnitDecl()] = PREDEF_DECL_TRANSLATION_UNIT_ID; 04187 if (Context.ObjCIdDecl) 04188 DeclIDs[Context.ObjCIdDecl] = PREDEF_DECL_OBJC_ID_ID; 04189 if (Context.ObjCSelDecl) 04190 DeclIDs[Context.ObjCSelDecl] = PREDEF_DECL_OBJC_SEL_ID; 04191 if (Context.ObjCClassDecl) 04192 DeclIDs[Context.ObjCClassDecl] = PREDEF_DECL_OBJC_CLASS_ID; 04193 if (Context.ObjCProtocolClassDecl) 04194 DeclIDs[Context.ObjCProtocolClassDecl] = PREDEF_DECL_OBJC_PROTOCOL_ID; 04195 if (Context.Int128Decl) 04196 DeclIDs[Context.Int128Decl] = PREDEF_DECL_INT_128_ID; 04197 if (Context.UInt128Decl) 04198 DeclIDs[Context.UInt128Decl] = PREDEF_DECL_UNSIGNED_INT_128_ID; 04199 if (Context.ObjCInstanceTypeDecl) 04200 DeclIDs[Context.ObjCInstanceTypeDecl] = PREDEF_DECL_OBJC_INSTANCETYPE_ID; 04201 if (Context.BuiltinVaListDecl) 04202 DeclIDs[Context.getBuiltinVaListDecl()] = PREDEF_DECL_BUILTIN_VA_LIST_ID; 04203 04204 if (!Chain) { 04205 // Make sure that we emit IdentifierInfos (and any attached 04206 // declarations) for builtins. We don't need to do this when we're 04207 // emitting chained PCH files, because all of the builtins will be 04208 // in the original PCH file. 04209 // FIXME: Modules won't like this at all. 04210 IdentifierTable &Table = PP.getIdentifierTable(); 04211 SmallVector<const char *, 32> BuiltinNames; 04212 if (!Context.getLangOpts().NoBuiltin) { 04213 Context.BuiltinInfo.GetBuiltinNames(BuiltinNames); 04214 } 04215 for (unsigned I = 0, N = BuiltinNames.size(); I != N; ++I) 04216 getIdentifierRef(&Table.get(BuiltinNames[I])); 04217 } 04218 04219 // If there are any out-of-date identifiers, bring them up to date. 04220 if (ExternalPreprocessorSource *ExtSource = PP.getExternalSource()) { 04221 // Find out-of-date identifiers. 04222 SmallVector<IdentifierInfo *, 4> OutOfDate; 04223 for (IdentifierTable::iterator ID = PP.getIdentifierTable().begin(), 04224 IDEnd = PP.getIdentifierTable().end(); 04225 ID != IDEnd; ++ID) { 04226 if (ID->second->isOutOfDate()) 04227 OutOfDate.push_back(ID->second); 04228 } 04229 04230 // Update the out-of-date identifiers. 04231 for (unsigned I = 0, N = OutOfDate.size(); I != N; ++I) { 04232 ExtSource->updateOutOfDateIdentifier(*OutOfDate[I]); 04233 } 04234 } 04235 04236 // If we saw any DeclContext updates before we started writing the AST file, 04237 // make sure all visible decls in those DeclContexts are written out. 04238 if (!UpdatedDeclContexts.empty()) { 04239 auto OldUpdatedDeclContexts = std::move(UpdatedDeclContexts); 04240 UpdatedDeclContexts.clear(); 04241 for (auto *DC : OldUpdatedDeclContexts) 04242 AddUpdatedDeclContext(DC); 04243 } 04244 04245 // Build a record containing all of the tentative definitions in this file, in 04246 // TentativeDefinitions order. Generally, this record will be empty for 04247 // headers. 04248 RecordData TentativeDefinitions; 04249 AddLazyVectorDecls(*this, SemaRef.TentativeDefinitions, TentativeDefinitions); 04250 04251 // Build a record containing all of the file scoped decls in this file. 04252 RecordData UnusedFileScopedDecls; 04253 if (!isModule) 04254 AddLazyVectorDecls(*this, SemaRef.UnusedFileScopedDecls, 04255 UnusedFileScopedDecls); 04256 04257 // Build a record containing all of the delegating constructors we still need 04258 // to resolve. 04259 RecordData DelegatingCtorDecls; 04260 if (!isModule) 04261 AddLazyVectorDecls(*this, SemaRef.DelegatingCtorDecls, DelegatingCtorDecls); 04262 04263 // Write the set of weak, undeclared identifiers. We always write the 04264 // entire table, since later PCH files in a PCH chain are only interested in 04265 // the results at the end of the chain. 04266 RecordData WeakUndeclaredIdentifiers; 04267 if (!SemaRef.WeakUndeclaredIdentifiers.empty()) { 04268 for (llvm::DenseMap<IdentifierInfo*,WeakInfo>::iterator 04269 I = SemaRef.WeakUndeclaredIdentifiers.begin(), 04270 E = SemaRef.WeakUndeclaredIdentifiers.end(); I != E; ++I) { 04271 AddIdentifierRef(I->first, WeakUndeclaredIdentifiers); 04272 AddIdentifierRef(I->second.getAlias(), WeakUndeclaredIdentifiers); 04273 AddSourceLocation(I->second.getLocation(), WeakUndeclaredIdentifiers); 04274 WeakUndeclaredIdentifiers.push_back(I->second.getUsed()); 04275 } 04276 } 04277 04278 // Build a record containing all of the locally-scoped extern "C" 04279 // declarations in this header file. Generally, this record will be 04280 // empty. 04281 RecordData LocallyScopedExternCDecls; 04282 // FIXME: This is filling in the AST file in densemap order which is 04283 // nondeterminstic! 04284 for (llvm::DenseMap<DeclarationName, NamedDecl *>::iterator 04285 TD = SemaRef.LocallyScopedExternCDecls.begin(), 04286 TDEnd = SemaRef.LocallyScopedExternCDecls.end(); 04287 TD != TDEnd; ++TD) { 04288 if (!TD->second->isFromASTFile()) 04289 AddDeclRef(TD->second, LocallyScopedExternCDecls); 04290 } 04291 04292 // Build a record containing all of the ext_vector declarations. 04293 RecordData ExtVectorDecls; 04294 AddLazyVectorDecls(*this, SemaRef.ExtVectorDecls, ExtVectorDecls); 04295 04296 // Build a record containing all of the VTable uses information. 04297 RecordData VTableUses; 04298 if (!SemaRef.VTableUses.empty()) { 04299 for (unsigned I = 0, N = SemaRef.VTableUses.size(); I != N; ++I) { 04300 AddDeclRef(SemaRef.VTableUses[I].first, VTableUses); 04301 AddSourceLocation(SemaRef.VTableUses[I].second, VTableUses); 04302 VTableUses.push_back(SemaRef.VTablesUsed[SemaRef.VTableUses[I].first]); 04303 } 04304 } 04305 04306 // Build a record containing all of the UnusedLocalTypedefNameCandidates. 04307 RecordData UnusedLocalTypedefNameCandidates; 04308 for (const TypedefNameDecl *TD : SemaRef.UnusedLocalTypedefNameCandidates) 04309 AddDeclRef(TD, UnusedLocalTypedefNameCandidates); 04310 04311 // Build a record containing all of dynamic classes declarations. 04312 RecordData DynamicClasses; 04313 AddLazyVectorDecls(*this, SemaRef.DynamicClasses, DynamicClasses); 04314 04315 // Build a record containing all of pending implicit instantiations. 04316 RecordData PendingInstantiations; 04317 for (std::deque<Sema::PendingImplicitInstantiation>::iterator 04318 I = SemaRef.PendingInstantiations.begin(), 04319 N = SemaRef.PendingInstantiations.end(); I != N; ++I) { 04320 AddDeclRef(I->first, PendingInstantiations); 04321 AddSourceLocation(I->second, PendingInstantiations); 04322 } 04323 assert(SemaRef.PendingLocalImplicitInstantiations.empty() && 04324 "There are local ones at end of translation unit!"); 04325 04326 // Build a record containing some declaration references. 04327 RecordData SemaDeclRefs; 04328 if (SemaRef.StdNamespace || SemaRef.StdBadAlloc) { 04329 AddDeclRef(SemaRef.getStdNamespace(), SemaDeclRefs); 04330 AddDeclRef(SemaRef.getStdBadAlloc(), SemaDeclRefs); 04331 } 04332 04333 RecordData CUDASpecialDeclRefs; 04334 if (Context.getcudaConfigureCallDecl()) { 04335 AddDeclRef(Context.getcudaConfigureCallDecl(), CUDASpecialDeclRefs); 04336 } 04337 04338 // Build a record containing all of the known namespaces. 04339 RecordData KnownNamespaces; 04340 for (llvm::MapVector<NamespaceDecl*, bool>::iterator 04341 I = SemaRef.KnownNamespaces.begin(), 04342 IEnd = SemaRef.KnownNamespaces.end(); 04343 I != IEnd; ++I) { 04344 if (!I->second) 04345 AddDeclRef(I->first, KnownNamespaces); 04346 } 04347 04348 // Build a record of all used, undefined objects that require definitions. 04349 RecordData UndefinedButUsed; 04350 04351 SmallVector<std::pair<NamedDecl *, SourceLocation>, 16> Undefined; 04352 SemaRef.getUndefinedButUsed(Undefined); 04353 for (SmallVectorImpl<std::pair<NamedDecl *, SourceLocation> >::iterator 04354 I = Undefined.begin(), E = Undefined.end(); I != E; ++I) { 04355 AddDeclRef(I->first, UndefinedButUsed); 04356 AddSourceLocation(I->second, UndefinedButUsed); 04357 } 04358 04359 // Write the control block 04360 WriteControlBlock(PP, Context, isysroot, OutputFile); 04361 04362 // Write the remaining AST contents. 04363 RecordData Record; 04364 Stream.EnterSubblock(AST_BLOCK_ID, 5); 04365 04366 // This is so that older clang versions, before the introduction 04367 // of the control block, can read and reject the newer PCH format. 04368 Record.clear(); 04369 Record.push_back(VERSION_MAJOR); 04370 Stream.EmitRecord(METADATA_OLD_FORMAT, Record); 04371 04372 // Create a lexical update block containing all of the declarations in the 04373 // translation unit that do not come from other AST files. 04374 const TranslationUnitDecl *TU = Context.getTranslationUnitDecl(); 04375 SmallVector<KindDeclIDPair, 64> NewGlobalDecls; 04376 for (const auto *I : TU->noload_decls()) { 04377 if (!I->isFromASTFile()) 04378 NewGlobalDecls.push_back(std::make_pair(I->getKind(), GetDeclRef(I))); 04379 } 04380 04381 llvm::BitCodeAbbrev *Abv = new llvm::BitCodeAbbrev(); 04382 Abv->Add(llvm::BitCodeAbbrevOp(TU_UPDATE_LEXICAL)); 04383 Abv->Add(llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::Blob)); 04384 unsigned TuUpdateLexicalAbbrev = Stream.EmitAbbrev(Abv); 04385 Record.clear(); 04386 Record.push_back(TU_UPDATE_LEXICAL); 04387 Stream.EmitRecordWithBlob(TuUpdateLexicalAbbrev, Record, 04388 data(NewGlobalDecls)); 04389 04390 // And a visible updates block for the translation unit. 04391 Abv = new llvm::BitCodeAbbrev(); 04392 Abv->Add(llvm::BitCodeAbbrevOp(UPDATE_VISIBLE)); 04393 Abv->Add(llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::VBR, 6)); 04394 Abv->Add(llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::Fixed, 32)); 04395 Abv->Add(llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::Blob)); 04396 UpdateVisibleAbbrev = Stream.EmitAbbrev(Abv); 04397 WriteDeclContextVisibleUpdate(TU); 04398 04399 // If the translation unit has an anonymous namespace, and we don't already 04400 // have an update block for it, write it as an update block. 04401 // FIXME: Why do we not do this if there's already an update block? 04402 if (NamespaceDecl *NS = TU->getAnonymousNamespace()) { 04403 ASTWriter::UpdateRecord &Record = DeclUpdates[TU]; 04404 if (Record.empty()) 04405 Record.push_back(DeclUpdate(UPD_CXX_ADDED_ANONYMOUS_NAMESPACE, NS)); 04406 } 04407 04408 // Add update records for all mangling numbers and static local numbers. 04409 // These aren't really update records, but this is a convenient way of 04410 // tagging this rare extra data onto the declarations. 04411 for (const auto &Number : Context.MangleNumbers) 04412 if (!Number.first->isFromASTFile()) 04413 DeclUpdates[Number.first].push_back(DeclUpdate(UPD_MANGLING_NUMBER, 04414 Number.second)); 04415 for (const auto &Number : Context.StaticLocalNumbers) 04416 if (!Number.first->isFromASTFile()) 04417 DeclUpdates[Number.first].push_back(DeclUpdate(UPD_STATIC_LOCAL_NUMBER, 04418 Number.second)); 04419 04420 // Make sure visible decls, added to DeclContexts previously loaded from 04421 // an AST file, are registered for serialization. 04422 for (SmallVectorImpl<const Decl *>::iterator 04423 I = UpdatingVisibleDecls.begin(), 04424 E = UpdatingVisibleDecls.end(); I != E; ++I) { 04425 GetDeclRef(*I); 04426 } 04427 04428 // Make sure all decls associated with an identifier are registered for 04429 // serialization. 04430 for (IdentifierTable::iterator ID = PP.getIdentifierTable().begin(), 04431 IDEnd = PP.getIdentifierTable().end(); 04432 ID != IDEnd; ++ID) { 04433 const IdentifierInfo *II = ID->second; 04434 if (!Chain || !II->isFromAST() || II->hasChangedSinceDeserialization()) { 04435 for (IdentifierResolver::iterator D = SemaRef.IdResolver.begin(II), 04436 DEnd = SemaRef.IdResolver.end(); 04437 D != DEnd; ++D) { 04438 GetDeclRef(*D); 04439 } 04440 } 04441 } 04442 04443 // Form the record of special types. 04444 RecordData SpecialTypes; 04445 AddTypeRef(Context.getRawCFConstantStringType(), SpecialTypes); 04446 AddTypeRef(Context.getFILEType(), SpecialTypes); 04447 AddTypeRef(Context.getjmp_bufType(), SpecialTypes); 04448 AddTypeRef(Context.getsigjmp_bufType(), SpecialTypes); 04449 AddTypeRef(Context.ObjCIdRedefinitionType, SpecialTypes); 04450 AddTypeRef(Context.ObjCClassRedefinitionType, SpecialTypes); 04451 AddTypeRef(Context.ObjCSelRedefinitionType, SpecialTypes); 04452 AddTypeRef(Context.getucontext_tType(), SpecialTypes); 04453 04454 if (Chain) { 04455 // Write the mapping information describing our module dependencies and how 04456 // each of those modules were mapped into our own offset/ID space, so that 04457 // the reader can build the appropriate mapping to its own offset/ID space. 04458 // The map consists solely of a blob with the following format: 04459 // *(module-name-len:i16 module-name:len*i8 04460 // source-location-offset:i32 04461 // identifier-id:i32 04462 // preprocessed-entity-id:i32 04463 // macro-definition-id:i32 04464 // submodule-id:i32 04465 // selector-id:i32 04466 // declaration-id:i32 04467 // c++-base-specifiers-id:i32 04468 // type-id:i32) 04469 // 04470 llvm::BitCodeAbbrev *Abbrev = new BitCodeAbbrev(); 04471 Abbrev->Add(BitCodeAbbrevOp(MODULE_OFFSET_MAP)); 04472 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); 04473 unsigned ModuleOffsetMapAbbrev = Stream.EmitAbbrev(Abbrev); 04474 SmallString<2048> Buffer; 04475 { 04476 llvm::raw_svector_ostream Out(Buffer); 04477 for (ModuleFile *M : Chain->ModuleMgr) { 04478 using namespace llvm::support; 04479 endian::Writer<little> LE(Out); 04480 StringRef FileName = M->FileName; 04481 LE.write<uint16_t>(FileName.size()); 04482 Out.write(FileName.data(), FileName.size()); 04483 04484 // Note: if a base ID was uint max, it would not be possible to load 04485 // another module after it or have more than one entity inside it. 04486 uint32_t None = std::numeric_limits<uint32_t>::max(); 04487 04488 auto writeBaseIDOrNone = [&](uint32_t BaseID, bool ShouldWrite) { 04489 assert(BaseID < std::numeric_limits<uint32_t>::max() && "base id too high"); 04490 if (ShouldWrite) 04491 LE.write<uint32_t>(BaseID); 04492 else 04493 LE.write<uint32_t>(None); 04494 }; 04495 04496 // These values should be unique within a chain, since they will be read 04497 // as keys into ContinuousRangeMaps. 04498 writeBaseIDOrNone(M->SLocEntryBaseOffset, M->LocalNumSLocEntries); 04499 writeBaseIDOrNone(M->BaseIdentifierID, M->LocalNumIdentifiers); 04500 writeBaseIDOrNone(M->BaseMacroID, M->LocalNumMacros); 04501 writeBaseIDOrNone(M->BasePreprocessedEntityID, 04502 M->NumPreprocessedEntities); 04503 writeBaseIDOrNone(M->BaseSubmoduleID, M->LocalNumSubmodules); 04504 writeBaseIDOrNone(M->BaseSelectorID, M->LocalNumSelectors); 04505 writeBaseIDOrNone(M->BaseDeclID, M->LocalNumDecls); 04506 writeBaseIDOrNone(M->BaseTypeIndex, M->LocalNumTypes); 04507 } 04508 } 04509 Record.clear(); 04510 Record.push_back(MODULE_OFFSET_MAP); 04511 Stream.EmitRecordWithBlob(ModuleOffsetMapAbbrev, Record, 04512 Buffer.data(), Buffer.size()); 04513 } 04514 04515 RecordData DeclUpdatesOffsetsRecord; 04516 04517 // Keep writing types, declarations, and declaration update records 04518 // until we've emitted all of them. 04519 Stream.EnterSubblock(DECLTYPES_BLOCK_ID, /*bits for abbreviations*/5); 04520 WriteTypeAbbrevs(); 04521 WriteDeclAbbrevs(); 04522 for (DeclsToRewriteTy::iterator I = DeclsToRewrite.begin(), 04523 E = DeclsToRewrite.end(); 04524 I != E; ++I) 04525 DeclTypesToEmit.push(const_cast<Decl*>(*I)); 04526 do { 04527 WriteDeclUpdatesBlocks(DeclUpdatesOffsetsRecord); 04528 while (!DeclTypesToEmit.empty()) { 04529 DeclOrType DOT = DeclTypesToEmit.front(); 04530 DeclTypesToEmit.pop(); 04531 if (DOT.isType()) 04532 WriteType(DOT.getType()); 04533 else 04534 WriteDecl(Context, DOT.getDecl()); 04535 } 04536 } while (!DeclUpdates.empty()); 04537 Stream.ExitBlock(); 04538 04539 DoneWritingDeclsAndTypes = true; 04540 04541 // These things can only be done once we've written out decls and types. 04542 WriteTypeDeclOffsets(); 04543 if (!DeclUpdatesOffsetsRecord.empty()) 04544 Stream.EmitRecord(DECL_UPDATE_OFFSETS, DeclUpdatesOffsetsRecord); 04545 WriteCXXBaseSpecifiersOffsets(); 04546 WriteFileDeclIDsMap(); 04547 WriteSourceManagerBlock(Context.getSourceManager(), PP, isysroot); 04548 04549 WriteComments(); 04550 WritePreprocessor(PP, isModule); 04551 WriteHeaderSearch(PP.getHeaderSearchInfo(), isysroot); 04552 WriteSelectors(SemaRef); 04553 WriteReferencedSelectorsPool(SemaRef); 04554 WriteIdentifierTable(PP, SemaRef.IdResolver, isModule); 04555 WriteFPPragmaOptions(SemaRef.getFPOptions()); 04556 WriteOpenCLExtensions(SemaRef); 04557 WritePragmaDiagnosticMappings(Context.getDiagnostics(), isModule); 04558 04559 // If we're emitting a module, write out the submodule information. 04560 if (WritingModule) 04561 WriteSubmodules(WritingModule); 04562 04563 Stream.EmitRecord(SPECIAL_TYPES, SpecialTypes); 04564 04565 // Write the record containing external, unnamed definitions. 04566 if (!EagerlyDeserializedDecls.empty()) 04567 Stream.EmitRecord(EAGERLY_DESERIALIZED_DECLS, EagerlyDeserializedDecls); 04568 04569 // Write the record containing tentative definitions. 04570 if (!TentativeDefinitions.empty()) 04571 Stream.EmitRecord(TENTATIVE_DEFINITIONS, TentativeDefinitions); 04572 04573 // Write the record containing unused file scoped decls. 04574 if (!UnusedFileScopedDecls.empty()) 04575 Stream.EmitRecord(UNUSED_FILESCOPED_DECLS, UnusedFileScopedDecls); 04576 04577 // Write the record containing weak undeclared identifiers. 04578 if (!WeakUndeclaredIdentifiers.empty()) 04579 Stream.EmitRecord(WEAK_UNDECLARED_IDENTIFIERS, 04580 WeakUndeclaredIdentifiers); 04581 04582 // Write the record containing locally-scoped extern "C" definitions. 04583 if (!LocallyScopedExternCDecls.empty()) 04584 Stream.EmitRecord(LOCALLY_SCOPED_EXTERN_C_DECLS, 04585 LocallyScopedExternCDecls); 04586 04587 // Write the record containing ext_vector type names. 04588 if (!ExtVectorDecls.empty()) 04589 Stream.EmitRecord(EXT_VECTOR_DECLS, ExtVectorDecls); 04590 04591 // Write the record containing VTable uses information. 04592 if (!VTableUses.empty()) 04593 Stream.EmitRecord(VTABLE_USES, VTableUses); 04594 04595 // Write the record containing dynamic classes declarations. 04596 if (!DynamicClasses.empty()) 04597 Stream.EmitRecord(DYNAMIC_CLASSES, DynamicClasses); 04598 04599 // Write the record containing potentially unused local typedefs. 04600 if (!UnusedLocalTypedefNameCandidates.empty()) 04601 Stream.EmitRecord(UNUSED_LOCAL_TYPEDEF_NAME_CANDIDATES, 04602 UnusedLocalTypedefNameCandidates); 04603 04604 // Write the record containing pending implicit instantiations. 04605 if (!PendingInstantiations.empty()) 04606 Stream.EmitRecord(PENDING_IMPLICIT_INSTANTIATIONS, PendingInstantiations); 04607 04608 // Write the record containing declaration references of Sema. 04609 if (!SemaDeclRefs.empty()) 04610 Stream.EmitRecord(SEMA_DECL_REFS, SemaDeclRefs); 04611 04612 // Write the record containing CUDA-specific declaration references. 04613 if (!CUDASpecialDeclRefs.empty()) 04614 Stream.EmitRecord(CUDA_SPECIAL_DECL_REFS, CUDASpecialDeclRefs); 04615 04616 // Write the delegating constructors. 04617 if (!DelegatingCtorDecls.empty()) 04618 Stream.EmitRecord(DELEGATING_CTORS, DelegatingCtorDecls); 04619 04620 // Write the known namespaces. 04621 if (!KnownNamespaces.empty()) 04622 Stream.EmitRecord(KNOWN_NAMESPACES, KnownNamespaces); 04623 04624 // Write the undefined internal functions and variables, and inline functions. 04625 if (!UndefinedButUsed.empty()) 04626 Stream.EmitRecord(UNDEFINED_BUT_USED, UndefinedButUsed); 04627 04628 // Write the visible updates to DeclContexts. 04629 for (auto *DC : UpdatedDeclContexts) 04630 WriteDeclContextVisibleUpdate(DC); 04631 04632 if (!WritingModule) { 04633 // Write the submodules that were imported, if any. 04634 struct ModuleInfo { 04635 uint64_t ID; 04636 Module *M; 04637 ModuleInfo(uint64_t ID, Module *M) : ID(ID), M(M) {} 04638 }; 04639 llvm::SmallVector<ModuleInfo, 64> Imports; 04640 for (const auto *I : Context.local_imports()) { 04641 assert(SubmoduleIDs.find(I->getImportedModule()) != SubmoduleIDs.end()); 04642 Imports.push_back(ModuleInfo(SubmoduleIDs[I->getImportedModule()], 04643 I->getImportedModule())); 04644 } 04645 04646 if (!Imports.empty()) { 04647 auto Cmp = [](const ModuleInfo &A, const ModuleInfo &B) { 04648 return A.ID < B.ID; 04649 }; 04650 auto Eq = [](const ModuleInfo &A, const ModuleInfo &B) { 04651 return A.ID == B.ID; 04652 }; 04653 04654 // Sort and deduplicate module IDs. 04655 std::sort(Imports.begin(), Imports.end(), Cmp); 04656 Imports.erase(std::unique(Imports.begin(), Imports.end(), Eq), 04657 Imports.end()); 04658 04659 RecordData ImportedModules; 04660 for (const auto &Import : Imports) { 04661 ImportedModules.push_back(Import.ID); 04662 // FIXME: If the module has macros imported then later has declarations 04663 // imported, this location won't be the right one as a location for the 04664 // declaration imports. 04665 AddSourceLocation(Import.M->MacroVisibilityLoc, ImportedModules); 04666 } 04667 04668 Stream.EmitRecord(IMPORTED_MODULES, ImportedModules); 04669 } 04670 } 04671 04672 WriteDeclReplacementsBlock(); 04673 WriteRedeclarations(); 04674 WriteMergedDecls(); 04675 WriteObjCCategories(); 04676 WriteLateParsedTemplates(SemaRef); 04677 if(!WritingModule) 04678 WriteOptimizePragmaOptions(SemaRef); 04679 04680 // Some simple statistics 04681 Record.clear(); 04682 Record.push_back(NumStatements); 04683 Record.push_back(NumMacros); 04684 Record.push_back(NumLexicalDeclContexts); 04685 Record.push_back(NumVisibleDeclContexts); 04686 Stream.EmitRecord(STATISTICS, Record); 04687 Stream.ExitBlock(); 04688 } 04689 04690 void ASTWriter::WriteDeclUpdatesBlocks(RecordDataImpl &OffsetsRecord) { 04691 if (DeclUpdates.empty()) 04692 return; 04693 04694 DeclUpdateMap LocalUpdates; 04695 LocalUpdates.swap(DeclUpdates); 04696 04697 for (auto &DeclUpdate : LocalUpdates) { 04698 const Decl *D = DeclUpdate.first; 04699 if (isRewritten(D)) 04700 continue; // The decl will be written completely,no need to store updates. 04701 04702 bool HasUpdatedBody = false; 04703 RecordData Record; 04704 for (auto &Update : DeclUpdate.second) { 04705 DeclUpdateKind Kind = (DeclUpdateKind)Update.getKind(); 04706 04707 Record.push_back(Kind); 04708 switch (Kind) { 04709 case UPD_CXX_ADDED_IMPLICIT_MEMBER: 04710 case UPD_CXX_ADDED_TEMPLATE_SPECIALIZATION: 04711 case UPD_CXX_ADDED_ANONYMOUS_NAMESPACE: 04712 assert(Update.getDecl() && "no decl to add?"); 04713 Record.push_back(GetDeclRef(Update.getDecl())); 04714 break; 04715 04716 case UPD_CXX_ADDED_FUNCTION_DEFINITION: 04717 // An updated body is emitted last, so that the reader doesn't need 04718 // to skip over the lazy body to reach statements for other records. 04719 Record.pop_back(); 04720 HasUpdatedBody = true; 04721 break; 04722 04723 case UPD_CXX_INSTANTIATED_STATIC_DATA_MEMBER: 04724 AddSourceLocation(Update.getLoc(), Record); 04725 break; 04726 04727 case UPD_CXX_INSTANTIATED_CLASS_DEFINITION: { 04728 auto *RD = cast<CXXRecordDecl>(D); 04729 AddUpdatedDeclContext(RD->getPrimaryContext()); 04730 AddCXXDefinitionData(RD, Record); 04731 Record.push_back(WriteDeclContextLexicalBlock( 04732 *Context, const_cast<CXXRecordDecl *>(RD))); 04733 04734 // This state is sometimes updated by template instantiation, when we 04735 // switch from the specialization referring to the template declaration 04736 // to it referring to the template definition. 04737 if (auto *MSInfo = RD->getMemberSpecializationInfo()) { 04738 Record.push_back(MSInfo->getTemplateSpecializationKind()); 04739 AddSourceLocation(MSInfo->getPointOfInstantiation(), Record); 04740 } else { 04741 auto *Spec = cast<ClassTemplateSpecializationDecl>(RD); 04742 Record.push_back(Spec->getTemplateSpecializationKind()); 04743 AddSourceLocation(Spec->getPointOfInstantiation(), Record); 04744 04745 // The instantiation might have been resolved to a partial 04746 // specialization. If so, record which one. 04747 auto From = Spec->getInstantiatedFrom(); 04748 if (auto PartialSpec = 04749 From.dyn_cast<ClassTemplatePartialSpecializationDecl*>()) { 04750 Record.push_back(true); 04751 AddDeclRef(PartialSpec, Record); 04752 AddTemplateArgumentList(&Spec->getTemplateInstantiationArgs(), 04753 Record); 04754 } else { 04755 Record.push_back(false); 04756 } 04757 } 04758 Record.push_back(RD->getTagKind()); 04759 AddSourceLocation(RD->getLocation(), Record); 04760 AddSourceLocation(RD->getLocStart(), Record); 04761 AddSourceLocation(RD->getRBraceLoc(), Record); 04762 04763 // Instantiation may change attributes; write them all out afresh. 04764 Record.push_back(D->hasAttrs()); 04765 if (Record.back()) 04766 WriteAttributes(llvm::makeArrayRef(D->getAttrs().begin(), 04767 D->getAttrs().size()), Record); 04768 04769 // FIXME: Ensure we don't get here for explicit instantiations. 04770 break; 04771 } 04772 04773 case UPD_CXX_RESOLVED_EXCEPTION_SPEC: 04774 addExceptionSpec( 04775 *this, 04776 cast<FunctionDecl>(D)->getType()->castAs<FunctionProtoType>(), 04777 Record); 04778 break; 04779 04780 case UPD_CXX_DEDUCED_RETURN_TYPE: 04781 Record.push_back(GetOrCreateTypeID(Update.getType())); 04782 break; 04783 04784 case UPD_DECL_MARKED_USED: 04785 break; 04786 04787 case UPD_MANGLING_NUMBER: 04788 case UPD_STATIC_LOCAL_NUMBER: 04789 Record.push_back(Update.getNumber()); 04790 break; 04791 case UPD_DECL_MARKED_OPENMP_THREADPRIVATE: 04792 AddSourceRange(D->getAttr<OMPThreadPrivateDeclAttr>()->getRange(), 04793 Record); 04794 break; 04795 } 04796 } 04797 04798 if (HasUpdatedBody) { 04799 const FunctionDecl *Def = cast<FunctionDecl>(D); 04800 Record.push_back(UPD_CXX_ADDED_FUNCTION_DEFINITION); 04801 Record.push_back(Def->isInlined()); 04802 AddSourceLocation(Def->getInnerLocStart(), Record); 04803 AddFunctionDefinition(Def, Record); 04804 if (auto *DD = dyn_cast<CXXDestructorDecl>(Def)) 04805 Record.push_back(GetDeclRef(DD->getOperatorDelete())); 04806 } 04807 04808 OffsetsRecord.push_back(GetDeclRef(D)); 04809 OffsetsRecord.push_back(Stream.GetCurrentBitNo()); 04810 04811 Stream.EmitRecord(DECL_UPDATES, Record); 04812 04813 // Flush any statements that were written as part of this update record. 04814 FlushStmts(); 04815 04816 // Flush C++ base specifiers, if there are any. 04817 FlushCXXBaseSpecifiers(); 04818 } 04819 } 04820 04821 void ASTWriter::WriteDeclReplacementsBlock() { 04822 if (ReplacedDecls.empty()) 04823 return; 04824 04825 RecordData Record; 04826 for (SmallVectorImpl<ReplacedDeclInfo>::iterator 04827 I = ReplacedDecls.begin(), E = ReplacedDecls.end(); I != E; ++I) { 04828 Record.push_back(I->ID); 04829 Record.push_back(I->Offset); 04830 Record.push_back(I->Loc); 04831 } 04832 Stream.EmitRecord(DECL_REPLACEMENTS, Record); 04833 } 04834 04835 void ASTWriter::AddSourceLocation(SourceLocation Loc, RecordDataImpl &Record) { 04836 Record.push_back(Loc.getRawEncoding()); 04837 } 04838 04839 void ASTWriter::AddSourceRange(SourceRange Range, RecordDataImpl &Record) { 04840 AddSourceLocation(Range.getBegin(), Record); 04841 AddSourceLocation(Range.getEnd(), Record); 04842 } 04843 04844 void ASTWriter::AddAPInt(const llvm::APInt &Value, RecordDataImpl &Record) { 04845 Record.push_back(Value.getBitWidth()); 04846 const uint64_t *Words = Value.getRawData(); 04847 Record.append(Words, Words + Value.getNumWords()); 04848 } 04849 04850 void ASTWriter::AddAPSInt(const llvm::APSInt &Value, RecordDataImpl &Record) { 04851 Record.push_back(Value.isUnsigned()); 04852 AddAPInt(Value, Record); 04853 } 04854 04855 void ASTWriter::AddAPFloat(const llvm::APFloat &Value, RecordDataImpl &Record) { 04856 AddAPInt(Value.bitcastToAPInt(), Record); 04857 } 04858 04859 void ASTWriter::AddIdentifierRef(const IdentifierInfo *II, RecordDataImpl &Record) { 04860 Record.push_back(getIdentifierRef(II)); 04861 } 04862 04863 IdentID ASTWriter::getIdentifierRef(const IdentifierInfo *II) { 04864 if (!II) 04865 return 0; 04866 04867 IdentID &ID = IdentifierIDs[II]; 04868 if (ID == 0) 04869 ID = NextIdentID++; 04870 return ID; 04871 } 04872 04873 MacroID ASTWriter::getMacroRef(MacroInfo *MI, const IdentifierInfo *Name) { 04874 // Don't emit builtin macros like __LINE__ to the AST file unless they 04875 // have been redefined by the header (in which case they are not 04876 // isBuiltinMacro). 04877 if (!MI || MI->isBuiltinMacro()) 04878 return 0; 04879 04880 MacroID &ID = MacroIDs[MI]; 04881 if (ID == 0) { 04882 ID = NextMacroID++; 04883 MacroInfoToEmitData Info = { Name, MI, ID }; 04884 MacroInfosToEmit.push_back(Info); 04885 } 04886 return ID; 04887 } 04888 04889 MacroID ASTWriter::getMacroID(MacroInfo *MI) { 04890 if (!MI || MI->isBuiltinMacro()) 04891 return 0; 04892 04893 assert(MacroIDs.find(MI) != MacroIDs.end() && "Macro not emitted!"); 04894 return MacroIDs[MI]; 04895 } 04896 04897 uint64_t ASTWriter::getMacroDirectivesOffset(const IdentifierInfo *Name) { 04898 assert(IdentMacroDirectivesOffsetMap[Name] && "not set!"); 04899 return IdentMacroDirectivesOffsetMap[Name]; 04900 } 04901 04902 void ASTWriter::AddSelectorRef(const Selector SelRef, RecordDataImpl &Record) { 04903 Record.push_back(getSelectorRef(SelRef)); 04904 } 04905 04906 SelectorID ASTWriter::getSelectorRef(Selector Sel) { 04907 if (Sel.getAsOpaquePtr() == nullptr) { 04908 return 0; 04909 } 04910 04911 SelectorID SID = SelectorIDs[Sel]; 04912 if (SID == 0 && Chain) { 04913 // This might trigger a ReadSelector callback, which will set the ID for 04914 // this selector. 04915 Chain->LoadSelector(Sel); 04916 SID = SelectorIDs[Sel]; 04917 } 04918 if (SID == 0) { 04919 SID = NextSelectorID++; 04920 SelectorIDs[Sel] = SID; 04921 } 04922 return SID; 04923 } 04924 04925 void ASTWriter::AddCXXTemporary(const CXXTemporary *Temp, RecordDataImpl &Record) { 04926 AddDeclRef(Temp->getDestructor(), Record); 04927 } 04928 04929 void ASTWriter::AddCXXBaseSpecifiersRef(CXXBaseSpecifier const *Bases, 04930 CXXBaseSpecifier const *BasesEnd, 04931 RecordDataImpl &Record) { 04932 assert(Bases != BasesEnd && "Empty base-specifier sets are not recorded"); 04933 CXXBaseSpecifiersToWrite.push_back( 04934 QueuedCXXBaseSpecifiers(NextCXXBaseSpecifiersID, 04935 Bases, BasesEnd)); 04936 Record.push_back(NextCXXBaseSpecifiersID++); 04937 } 04938 04939 void ASTWriter::AddTemplateArgumentLocInfo(TemplateArgument::ArgKind Kind, 04940 const TemplateArgumentLocInfo &Arg, 04941 RecordDataImpl &Record) { 04942 switch (Kind) { 04943 case TemplateArgument::Expression: 04944 AddStmt(Arg.getAsExpr()); 04945 break; 04946 case TemplateArgument::Type: 04947 AddTypeSourceInfo(Arg.getAsTypeSourceInfo(), Record); 04948 break; 04949 case TemplateArgument::Template: 04950 AddNestedNameSpecifierLoc(Arg.getTemplateQualifierLoc(), Record); 04951 AddSourceLocation(Arg.getTemplateNameLoc(), Record); 04952 break; 04953 case TemplateArgument::TemplateExpansion: 04954 AddNestedNameSpecifierLoc(Arg.getTemplateQualifierLoc(), Record); 04955 AddSourceLocation(Arg.getTemplateNameLoc(), Record); 04956 AddSourceLocation(Arg.getTemplateEllipsisLoc(), Record); 04957 break; 04958 case TemplateArgument::Null: 04959 case TemplateArgument::Integral: 04960 case TemplateArgument::Declaration: 04961 case TemplateArgument::NullPtr: 04962 case TemplateArgument::Pack: 04963 // FIXME: Is this right? 04964 break; 04965 } 04966 } 04967 04968 void ASTWriter::AddTemplateArgumentLoc(const TemplateArgumentLoc &Arg, 04969 RecordDataImpl &Record) { 04970 AddTemplateArgument(Arg.getArgument(), Record); 04971 04972 if (Arg.getArgument().getKind() == TemplateArgument::Expression) { 04973 bool InfoHasSameExpr 04974 = Arg.getArgument().getAsExpr() == Arg.getLocInfo().getAsExpr(); 04975 Record.push_back(InfoHasSameExpr); 04976 if (InfoHasSameExpr) 04977 return; // Avoid storing the same expr twice. 04978 } 04979 AddTemplateArgumentLocInfo(Arg.getArgument().getKind(), Arg.getLocInfo(), 04980 Record); 04981 } 04982 04983 void ASTWriter::AddTypeSourceInfo(TypeSourceInfo *TInfo, 04984 RecordDataImpl &Record) { 04985 if (!TInfo) { 04986 AddTypeRef(QualType(), Record); 04987 return; 04988 } 04989 04990 AddTypeLoc(TInfo->getTypeLoc(), Record); 04991 } 04992 04993 void ASTWriter::AddTypeLoc(TypeLoc TL, RecordDataImpl &Record) { 04994 AddTypeRef(TL.getType(), Record); 04995 04996 TypeLocWriter TLW(*this, Record); 04997 for (; !TL.isNull(); TL = TL.getNextTypeLoc()) 04998 TLW.Visit(TL); 04999 } 05000 05001 void ASTWriter::AddTypeRef(QualType T, RecordDataImpl &Record) { 05002 Record.push_back(GetOrCreateTypeID(T)); 05003 } 05004 05005 TypeID ASTWriter::GetOrCreateTypeID( QualType T) { 05006 assert(Context); 05007 return MakeTypeID(*Context, T, 05008 std::bind1st(std::mem_fun(&ASTWriter::GetOrCreateTypeIdx), this)); 05009 } 05010 05011 TypeID ASTWriter::getTypeID(QualType T) const { 05012 assert(Context); 05013 return MakeTypeID(*Context, T, 05014 std::bind1st(std::mem_fun(&ASTWriter::getTypeIdx), this)); 05015 } 05016 05017 TypeIdx ASTWriter::GetOrCreateTypeIdx(QualType T) { 05018 if (T.isNull()) 05019 return TypeIdx(); 05020 assert(!T.getLocalFastQualifiers()); 05021 05022 TypeIdx &Idx = TypeIdxs[T]; 05023 if (Idx.getIndex() == 0) { 05024 if (DoneWritingDeclsAndTypes) { 05025 assert(0 && "New type seen after serializing all the types to emit!"); 05026 return TypeIdx(); 05027 } 05028 05029 // We haven't seen this type before. Assign it a new ID and put it 05030 // into the queue of types to emit. 05031 Idx = TypeIdx(NextTypeID++); 05032 DeclTypesToEmit.push(T); 05033 } 05034 return Idx; 05035 } 05036 05037 TypeIdx ASTWriter::getTypeIdx(QualType T) const { 05038 if (T.isNull()) 05039 return TypeIdx(); 05040 assert(!T.getLocalFastQualifiers()); 05041 05042 TypeIdxMap::const_iterator I = TypeIdxs.find(T); 05043 assert(I != TypeIdxs.end() && "Type not emitted!"); 05044 return I->second; 05045 } 05046 05047 void ASTWriter::AddDeclRef(const Decl *D, RecordDataImpl &Record) { 05048 Record.push_back(GetDeclRef(D)); 05049 } 05050 05051 DeclID ASTWriter::GetDeclRef(const Decl *D) { 05052 assert(WritingAST && "Cannot request a declaration ID before AST writing"); 05053 05054 if (!D) { 05055 return 0; 05056 } 05057 05058 // If D comes from an AST file, its declaration ID is already known and 05059 // fixed. 05060 if (D->isFromASTFile()) 05061 return D->getGlobalID(); 05062 05063 assert(!(reinterpret_cast<uintptr_t>(D) & 0x01) && "Invalid decl pointer"); 05064 DeclID &ID = DeclIDs[D]; 05065 if (ID == 0) { 05066 if (DoneWritingDeclsAndTypes) { 05067 assert(0 && "New decl seen after serializing all the decls to emit!"); 05068 return 0; 05069 } 05070 05071 // We haven't seen this declaration before. Give it a new ID and 05072 // enqueue it in the list of declarations to emit. 05073 ID = NextDeclID++; 05074 DeclTypesToEmit.push(const_cast<Decl *>(D)); 05075 } 05076 05077 return ID; 05078 } 05079 05080 DeclID ASTWriter::getDeclID(const Decl *D) { 05081 if (!D) 05082 return 0; 05083 05084 // If D comes from an AST file, its declaration ID is already known and 05085 // fixed. 05086 if (D->isFromASTFile()) 05087 return D->getGlobalID(); 05088 05089 assert(DeclIDs.find(D) != DeclIDs.end() && "Declaration not emitted!"); 05090 return DeclIDs[D]; 05091 } 05092 05093 void ASTWriter::associateDeclWithFile(const Decl *D, DeclID ID) { 05094 assert(ID); 05095 assert(D); 05096 05097 SourceLocation Loc = D->getLocation(); 05098 if (Loc.isInvalid()) 05099 return; 05100 05101 // We only keep track of the file-level declarations of each file. 05102 if (!D->getLexicalDeclContext()->isFileContext()) 05103 return; 05104 // FIXME: ParmVarDecls that are part of a function type of a parameter of 05105 // a function/objc method, should not have TU as lexical context. 05106 if (isa<ParmVarDecl>(D)) 05107 return; 05108 05109 SourceManager &SM = Context->getSourceManager(); 05110 SourceLocation FileLoc = SM.getFileLoc(Loc); 05111 assert(SM.isLocalSourceLocation(FileLoc)); 05112 FileID FID; 05113 unsigned Offset; 05114 std::tie(FID, Offset) = SM.getDecomposedLoc(FileLoc); 05115 if (FID.isInvalid()) 05116 return; 05117 assert(SM.getSLocEntry(FID).isFile()); 05118 05119 DeclIDInFileInfo *&Info = FileDeclIDs[FID]; 05120 if (!Info) 05121 Info = new DeclIDInFileInfo(); 05122 05123 std::pair<unsigned, serialization::DeclID> LocDecl(Offset, ID); 05124 LocDeclIDsTy &Decls = Info->DeclIDs; 05125 05126 if (Decls.empty() || Decls.back().first <= Offset) { 05127 Decls.push_back(LocDecl); 05128 return; 05129 } 05130 05131 LocDeclIDsTy::iterator I = 05132 std::upper_bound(Decls.begin(), Decls.end(), LocDecl, llvm::less_first()); 05133 05134 Decls.insert(I, LocDecl); 05135 } 05136 05137 void ASTWriter::AddDeclarationName(DeclarationName Name, RecordDataImpl &Record) { 05138 // FIXME: Emit a stable enum for NameKind. 0 = Identifier etc. 05139 Record.push_back(Name.getNameKind()); 05140 switch (Name.getNameKind()) { 05141 case DeclarationName::Identifier: 05142 AddIdentifierRef(Name.getAsIdentifierInfo(), Record); 05143 break; 05144 05145 case DeclarationName::ObjCZeroArgSelector: 05146 case DeclarationName::ObjCOneArgSelector: 05147 case DeclarationName::ObjCMultiArgSelector: 05148 AddSelectorRef(Name.getObjCSelector(), Record); 05149 break; 05150 05151 case DeclarationName::CXXConstructorName: 05152 case DeclarationName::CXXDestructorName: 05153 case DeclarationName::CXXConversionFunctionName: 05154 AddTypeRef(Name.getCXXNameType(), Record); 05155 break; 05156 05157 case DeclarationName::CXXOperatorName: 05158 Record.push_back(Name.getCXXOverloadedOperator()); 05159 break; 05160 05161 case DeclarationName::CXXLiteralOperatorName: 05162 AddIdentifierRef(Name.getCXXLiteralIdentifier(), Record); 05163 break; 05164 05165 case DeclarationName::CXXUsingDirective: 05166 // No extra data to emit 05167 break; 05168 } 05169 } 05170 05171 unsigned ASTWriter::getAnonymousDeclarationNumber(const NamedDecl *D) { 05172 assert(needsAnonymousDeclarationNumber(D) && 05173 "expected an anonymous declaration"); 05174 05175 // Number the anonymous declarations within this context, if we've not 05176 // already done so. 05177 auto It = AnonymousDeclarationNumbers.find(D); 05178 if (It == AnonymousDeclarationNumbers.end()) { 05179 unsigned Index = 0; 05180 for (Decl *LexicalD : D->getLexicalDeclContext()->decls()) { 05181 auto *ND = dyn_cast<NamedDecl>(LexicalD); 05182 if (!ND || !needsAnonymousDeclarationNumber(ND)) 05183 continue; 05184 AnonymousDeclarationNumbers[ND] = Index++; 05185 } 05186 05187 It = AnonymousDeclarationNumbers.find(D); 05188 assert(It != AnonymousDeclarationNumbers.end() && 05189 "declaration not found within its lexical context"); 05190 } 05191 05192 return It->second; 05193 } 05194 05195 void ASTWriter::AddDeclarationNameLoc(const DeclarationNameLoc &DNLoc, 05196 DeclarationName Name, RecordDataImpl &Record) { 05197 switch (Name.getNameKind()) { 05198 case DeclarationName::CXXConstructorName: 05199 case DeclarationName::CXXDestructorName: 05200 case DeclarationName::CXXConversionFunctionName: 05201 AddTypeSourceInfo(DNLoc.NamedType.TInfo, Record); 05202 break; 05203 05204 case DeclarationName::CXXOperatorName: 05205 AddSourceLocation( 05206 SourceLocation::getFromRawEncoding(DNLoc.CXXOperatorName.BeginOpNameLoc), 05207 Record); 05208 AddSourceLocation( 05209 SourceLocation::getFromRawEncoding(DNLoc.CXXOperatorName.EndOpNameLoc), 05210 Record); 05211 break; 05212 05213 case DeclarationName::CXXLiteralOperatorName: 05214 AddSourceLocation( 05215 SourceLocation::getFromRawEncoding(DNLoc.CXXLiteralOperatorName.OpNameLoc), 05216 Record); 05217 break; 05218 05219 case DeclarationName::Identifier: 05220 case DeclarationName::ObjCZeroArgSelector: 05221 case DeclarationName::ObjCOneArgSelector: 05222 case DeclarationName::ObjCMultiArgSelector: 05223 case DeclarationName::CXXUsingDirective: 05224 break; 05225 } 05226 } 05227 05228 void ASTWriter::AddDeclarationNameInfo(const DeclarationNameInfo &NameInfo, 05229 RecordDataImpl &Record) { 05230 AddDeclarationName(NameInfo.getName(), Record); 05231 AddSourceLocation(NameInfo.getLoc(), Record); 05232 AddDeclarationNameLoc(NameInfo.getInfo(), NameInfo.getName(), Record); 05233 } 05234 05235 void ASTWriter::AddQualifierInfo(const QualifierInfo &Info, 05236 RecordDataImpl &Record) { 05237 AddNestedNameSpecifierLoc(Info.QualifierLoc, Record); 05238 Record.push_back(Info.NumTemplParamLists); 05239 for (unsigned i=0, e=Info.NumTemplParamLists; i != e; ++i) 05240 AddTemplateParameterList(Info.TemplParamLists[i], Record); 05241 } 05242 05243 void ASTWriter::AddNestedNameSpecifier(NestedNameSpecifier *NNS, 05244 RecordDataImpl &Record) { 05245 // Nested name specifiers usually aren't too long. I think that 8 would 05246 // typically accommodate the vast majority. 05247 SmallVector<NestedNameSpecifier *, 8> NestedNames; 05248 05249 // Push each of the NNS's onto a stack for serialization in reverse order. 05250 while (NNS) { 05251 NestedNames.push_back(NNS); 05252 NNS = NNS->getPrefix(); 05253 } 05254 05255 Record.push_back(NestedNames.size()); 05256 while(!NestedNames.empty()) { 05257 NNS = NestedNames.pop_back_val(); 05258 NestedNameSpecifier::SpecifierKind Kind = NNS->getKind(); 05259 Record.push_back(Kind); 05260 switch (Kind) { 05261 case NestedNameSpecifier::Identifier: 05262 AddIdentifierRef(NNS->getAsIdentifier(), Record); 05263 break; 05264 05265 case NestedNameSpecifier::Namespace: 05266 AddDeclRef(NNS->getAsNamespace(), Record); 05267 break; 05268 05269 case NestedNameSpecifier::NamespaceAlias: 05270 AddDeclRef(NNS->getAsNamespaceAlias(), Record); 05271 break; 05272 05273 case NestedNameSpecifier::TypeSpec: 05274 case NestedNameSpecifier::TypeSpecWithTemplate: 05275 AddTypeRef(QualType(NNS->getAsType(), 0), Record); 05276 Record.push_back(Kind == NestedNameSpecifier::TypeSpecWithTemplate); 05277 break; 05278 05279 case NestedNameSpecifier::Global: 05280 // Don't need to write an associated value. 05281 break; 05282 05283 case NestedNameSpecifier::Super: 05284 AddDeclRef(NNS->getAsRecordDecl(), Record); 05285 break; 05286 } 05287 } 05288 } 05289 05290 void ASTWriter::AddNestedNameSpecifierLoc(NestedNameSpecifierLoc NNS, 05291 RecordDataImpl &Record) { 05292 // Nested name specifiers usually aren't too long. I think that 8 would 05293 // typically accommodate the vast majority. 05294 SmallVector<NestedNameSpecifierLoc , 8> NestedNames; 05295 05296 // Push each of the nested-name-specifiers's onto a stack for 05297 // serialization in reverse order. 05298 while (NNS) { 05299 NestedNames.push_back(NNS); 05300 NNS = NNS.getPrefix(); 05301 } 05302 05303 Record.push_back(NestedNames.size()); 05304 while(!NestedNames.empty()) { 05305 NNS = NestedNames.pop_back_val(); 05306 NestedNameSpecifier::SpecifierKind Kind 05307 = NNS.getNestedNameSpecifier()->getKind(); 05308 Record.push_back(Kind); 05309 switch (Kind) { 05310 case NestedNameSpecifier::Identifier: 05311 AddIdentifierRef(NNS.getNestedNameSpecifier()->getAsIdentifier(), Record); 05312 AddSourceRange(NNS.getLocalSourceRange(), Record); 05313 break; 05314 05315 case NestedNameSpecifier::Namespace: 05316 AddDeclRef(NNS.getNestedNameSpecifier()->getAsNamespace(), Record); 05317 AddSourceRange(NNS.getLocalSourceRange(), Record); 05318 break; 05319 05320 case NestedNameSpecifier::NamespaceAlias: 05321 AddDeclRef(NNS.getNestedNameSpecifier()->getAsNamespaceAlias(), Record); 05322 AddSourceRange(NNS.getLocalSourceRange(), Record); 05323 break; 05324 05325 case NestedNameSpecifier::TypeSpec: 05326 case NestedNameSpecifier::TypeSpecWithTemplate: 05327 Record.push_back(Kind == NestedNameSpecifier::TypeSpecWithTemplate); 05328 AddTypeLoc(NNS.getTypeLoc(), Record); 05329 AddSourceLocation(NNS.getLocalSourceRange().getEnd(), Record); 05330 break; 05331 05332 case NestedNameSpecifier::Global: 05333 AddSourceLocation(NNS.getLocalSourceRange().getEnd(), Record); 05334 break; 05335 05336 case NestedNameSpecifier::Super: 05337 AddDeclRef(NNS.getNestedNameSpecifier()->getAsRecordDecl(), Record); 05338 AddSourceRange(NNS.getLocalSourceRange(), Record); 05339 break; 05340 } 05341 } 05342 } 05343 05344 void ASTWriter::AddTemplateName(TemplateName Name, RecordDataImpl &Record) { 05345 TemplateName::NameKind Kind = Name.getKind(); 05346 Record.push_back(Kind); 05347 switch (Kind) { 05348 case TemplateName::Template: 05349 AddDeclRef(Name.getAsTemplateDecl(), Record); 05350 break; 05351 05352 case TemplateName::OverloadedTemplate: { 05353 OverloadedTemplateStorage *OvT = Name.getAsOverloadedTemplate(); 05354 Record.push_back(OvT->size()); 05355 for (OverloadedTemplateStorage::iterator I = OvT->begin(), E = OvT->end(); 05356 I != E; ++I) 05357 AddDeclRef(*I, Record); 05358 break; 05359 } 05360 05361 case TemplateName::QualifiedTemplate: { 05362 QualifiedTemplateName *QualT = Name.getAsQualifiedTemplateName(); 05363 AddNestedNameSpecifier(QualT->getQualifier(), Record); 05364 Record.push_back(QualT->hasTemplateKeyword()); 05365 AddDeclRef(QualT->getTemplateDecl(), Record); 05366 break; 05367 } 05368 05369 case TemplateName::DependentTemplate: { 05370 DependentTemplateName *DepT = Name.getAsDependentTemplateName(); 05371 AddNestedNameSpecifier(DepT->getQualifier(), Record); 05372 Record.push_back(DepT->isIdentifier()); 05373 if (DepT->isIdentifier()) 05374 AddIdentifierRef(DepT->getIdentifier(), Record); 05375 else 05376 Record.push_back(DepT->getOperator()); 05377 break; 05378 } 05379 05380 case TemplateName::SubstTemplateTemplateParm: { 05381 SubstTemplateTemplateParmStorage *subst 05382 = Name.getAsSubstTemplateTemplateParm(); 05383 AddDeclRef(subst->getParameter(), Record); 05384 AddTemplateName(subst->getReplacement(), Record); 05385 break; 05386 } 05387 05388 case TemplateName::SubstTemplateTemplateParmPack: { 05389 SubstTemplateTemplateParmPackStorage *SubstPack 05390 = Name.getAsSubstTemplateTemplateParmPack(); 05391 AddDeclRef(SubstPack->getParameterPack(), Record); 05392 AddTemplateArgument(SubstPack->getArgumentPack(), Record); 05393 break; 05394 } 05395 } 05396 } 05397 05398 void ASTWriter::AddTemplateArgument(const TemplateArgument &Arg, 05399 RecordDataImpl &Record) { 05400 Record.push_back(Arg.getKind()); 05401 switch (Arg.getKind()) { 05402 case TemplateArgument::Null: 05403 break; 05404 case TemplateArgument::Type: 05405 AddTypeRef(Arg.getAsType(), Record); 05406 break; 05407 case TemplateArgument::Declaration: 05408 AddDeclRef(Arg.getAsDecl(), Record); 05409 AddTypeRef(Arg.getParamTypeForDecl(), Record); 05410 break; 05411 case TemplateArgument::NullPtr: 05412 AddTypeRef(Arg.getNullPtrType(), Record); 05413 break; 05414 case TemplateArgument::Integral: 05415 AddAPSInt(Arg.getAsIntegral(), Record); 05416 AddTypeRef(Arg.getIntegralType(), Record); 05417 break; 05418 case TemplateArgument::Template: 05419 AddTemplateName(Arg.getAsTemplateOrTemplatePattern(), Record); 05420 break; 05421 case TemplateArgument::TemplateExpansion: 05422 AddTemplateName(Arg.getAsTemplateOrTemplatePattern(), Record); 05423 if (Optional<unsigned> NumExpansions = Arg.getNumTemplateExpansions()) 05424 Record.push_back(*NumExpansions + 1); 05425 else 05426 Record.push_back(0); 05427 break; 05428 case TemplateArgument::Expression: 05429 AddStmt(Arg.getAsExpr()); 05430 break; 05431 case TemplateArgument::Pack: 05432 Record.push_back(Arg.pack_size()); 05433 for (const auto &P : Arg.pack_elements()) 05434 AddTemplateArgument(P, Record); 05435 break; 05436 } 05437 } 05438 05439 void 05440 ASTWriter::AddTemplateParameterList(const TemplateParameterList *TemplateParams, 05441 RecordDataImpl &Record) { 05442 assert(TemplateParams && "No TemplateParams!"); 05443 AddSourceLocation(TemplateParams->getTemplateLoc(), Record); 05444 AddSourceLocation(TemplateParams->getLAngleLoc(), Record); 05445 AddSourceLocation(TemplateParams->getRAngleLoc(), Record); 05446 Record.push_back(TemplateParams->size()); 05447 for (TemplateParameterList::const_iterator 05448 P = TemplateParams->begin(), PEnd = TemplateParams->end(); 05449 P != PEnd; ++P) 05450 AddDeclRef(*P, Record); 05451 } 05452 05453 /// \brief Emit a template argument list. 05454 void 05455 ASTWriter::AddTemplateArgumentList(const TemplateArgumentList *TemplateArgs, 05456 RecordDataImpl &Record) { 05457 assert(TemplateArgs && "No TemplateArgs!"); 05458 Record.push_back(TemplateArgs->size()); 05459 for (int i=0, e = TemplateArgs->size(); i != e; ++i) 05460 AddTemplateArgument(TemplateArgs->get(i), Record); 05461 } 05462 05463 void 05464 ASTWriter::AddASTTemplateArgumentListInfo 05465 (const ASTTemplateArgumentListInfo *ASTTemplArgList, RecordDataImpl &Record) { 05466 assert(ASTTemplArgList && "No ASTTemplArgList!"); 05467 AddSourceLocation(ASTTemplArgList->LAngleLoc, Record); 05468 AddSourceLocation(ASTTemplArgList->RAngleLoc, Record); 05469 Record.push_back(ASTTemplArgList->NumTemplateArgs); 05470 const TemplateArgumentLoc *TemplArgs = ASTTemplArgList->getTemplateArgs(); 05471 for (int i=0, e = ASTTemplArgList->NumTemplateArgs; i != e; ++i) 05472 AddTemplateArgumentLoc(TemplArgs[i], Record); 05473 } 05474 05475 void 05476 ASTWriter::AddUnresolvedSet(const ASTUnresolvedSet &Set, RecordDataImpl &Record) { 05477 Record.push_back(Set.size()); 05478 for (ASTUnresolvedSet::const_iterator 05479 I = Set.begin(), E = Set.end(); I != E; ++I) { 05480 AddDeclRef(I.getDecl(), Record); 05481 Record.push_back(I.getAccess()); 05482 } 05483 } 05484 05485 void ASTWriter::AddCXXBaseSpecifier(const CXXBaseSpecifier &Base, 05486 RecordDataImpl &Record) { 05487 Record.push_back(Base.isVirtual()); 05488 Record.push_back(Base.isBaseOfClass()); 05489 Record.push_back(Base.getAccessSpecifierAsWritten()); 05490 Record.push_back(Base.getInheritConstructors()); 05491 AddTypeSourceInfo(Base.getTypeSourceInfo(), Record); 05492 AddSourceRange(Base.getSourceRange(), Record); 05493 AddSourceLocation(Base.isPackExpansion()? Base.getEllipsisLoc() 05494 : SourceLocation(), 05495 Record); 05496 } 05497 05498 void ASTWriter::FlushCXXBaseSpecifiers() { 05499 RecordData Record; 05500 for (unsigned I = 0, N = CXXBaseSpecifiersToWrite.size(); I != N; ++I) { 05501 Record.clear(); 05502 05503 // Record the offset of this base-specifier set. 05504 unsigned Index = CXXBaseSpecifiersToWrite[I].ID - 1; 05505 if (Index == CXXBaseSpecifiersOffsets.size()) 05506 CXXBaseSpecifiersOffsets.push_back(Stream.GetCurrentBitNo()); 05507 else { 05508 if (Index > CXXBaseSpecifiersOffsets.size()) 05509 CXXBaseSpecifiersOffsets.resize(Index + 1); 05510 CXXBaseSpecifiersOffsets[Index] = Stream.GetCurrentBitNo(); 05511 } 05512 05513 const CXXBaseSpecifier *B = CXXBaseSpecifiersToWrite[I].Bases, 05514 *BEnd = CXXBaseSpecifiersToWrite[I].BasesEnd; 05515 Record.push_back(BEnd - B); 05516 for (; B != BEnd; ++B) 05517 AddCXXBaseSpecifier(*B, Record); 05518 Stream.EmitRecord(serialization::DECL_CXX_BASE_SPECIFIERS, Record); 05519 05520 // Flush any expressions that were written as part of the base specifiers. 05521 FlushStmts(); 05522 } 05523 05524 CXXBaseSpecifiersToWrite.clear(); 05525 } 05526 05527 void ASTWriter::AddCXXCtorInitializers( 05528 const CXXCtorInitializer * const *CtorInitializers, 05529 unsigned NumCtorInitializers, 05530 RecordDataImpl &Record) { 05531 Record.push_back(NumCtorInitializers); 05532 for (unsigned i=0; i != NumCtorInitializers; ++i) { 05533 const CXXCtorInitializer *Init = CtorInitializers[i]; 05534 05535 if (Init->isBaseInitializer()) { 05536 Record.push_back(CTOR_INITIALIZER_BASE); 05537 AddTypeSourceInfo(Init->getTypeSourceInfo(), Record); 05538 Record.push_back(Init->isBaseVirtual()); 05539 } else if (Init->isDelegatingInitializer()) { 05540 Record.push_back(CTOR_INITIALIZER_DELEGATING); 05541 AddTypeSourceInfo(Init->getTypeSourceInfo(), Record); 05542 } else if (Init->isMemberInitializer()){ 05543 Record.push_back(CTOR_INITIALIZER_MEMBER); 05544 AddDeclRef(Init->getMember(), Record); 05545 } else { 05546 Record.push_back(CTOR_INITIALIZER_INDIRECT_MEMBER); 05547 AddDeclRef(Init->getIndirectMember(), Record); 05548 } 05549 05550 AddSourceLocation(Init->getMemberLocation(), Record); 05551 AddStmt(Init->getInit()); 05552 AddSourceLocation(Init->getLParenLoc(), Record); 05553 AddSourceLocation(Init->getRParenLoc(), Record); 05554 Record.push_back(Init->isWritten()); 05555 if (Init->isWritten()) { 05556 Record.push_back(Init->getSourceOrder()); 05557 } else { 05558 Record.push_back(Init->getNumArrayIndices()); 05559 for (unsigned i=0, e=Init->getNumArrayIndices(); i != e; ++i) 05560 AddDeclRef(Init->getArrayIndex(i), Record); 05561 } 05562 } 05563 } 05564 05565 void ASTWriter::AddCXXDefinitionData(const CXXRecordDecl *D, RecordDataImpl &Record) { 05566 auto &Data = D->data(); 05567 Record.push_back(Data.IsLambda); 05568 Record.push_back(Data.UserDeclaredConstructor); 05569 Record.push_back(Data.UserDeclaredSpecialMembers); 05570 Record.push_back(Data.Aggregate); 05571 Record.push_back(Data.PlainOldData); 05572 Record.push_back(Data.Empty); 05573 Record.push_back(Data.Polymorphic); 05574 Record.push_back(Data.Abstract); 05575 Record.push_back(Data.IsStandardLayout); 05576 Record.push_back(Data.HasNoNonEmptyBases); 05577 Record.push_back(Data.HasPrivateFields); 05578 Record.push_back(Data.HasProtectedFields); 05579 Record.push_back(Data.HasPublicFields); 05580 Record.push_back(Data.HasMutableFields); 05581 Record.push_back(Data.HasVariantMembers); 05582 Record.push_back(Data.HasOnlyCMembers); 05583 Record.push_back(Data.HasInClassInitializer); 05584 Record.push_back(Data.HasUninitializedReferenceMember); 05585 Record.push_back(Data.NeedOverloadResolutionForMoveConstructor); 05586 Record.push_back(Data.NeedOverloadResolutionForMoveAssignment); 05587 Record.push_back(Data.NeedOverloadResolutionForDestructor); 05588 Record.push_back(Data.DefaultedMoveConstructorIsDeleted); 05589 Record.push_back(Data.DefaultedMoveAssignmentIsDeleted); 05590 Record.push_back(Data.DefaultedDestructorIsDeleted); 05591 Record.push_back(Data.HasTrivialSpecialMembers); 05592 Record.push_back(Data.DeclaredNonTrivialSpecialMembers); 05593 Record.push_back(Data.HasIrrelevantDestructor); 05594 Record.push_back(Data.HasConstexprNonCopyMoveConstructor); 05595 Record.push_back(Data.DefaultedDefaultConstructorIsConstexpr); 05596 Record.push_back(Data.HasConstexprDefaultConstructor); 05597 Record.push_back(Data.HasNonLiteralTypeFieldsOrBases); 05598 Record.push_back(Data.ComputedVisibleConversions); 05599 Record.push_back(Data.UserProvidedDefaultConstructor); 05600 Record.push_back(Data.DeclaredSpecialMembers); 05601 Record.push_back(Data.ImplicitCopyConstructorHasConstParam); 05602 Record.push_back(Data.ImplicitCopyAssignmentHasConstParam); 05603 Record.push_back(Data.HasDeclaredCopyConstructorWithConstParam); 05604 Record.push_back(Data.HasDeclaredCopyAssignmentWithConstParam); 05605 // IsLambda bit is already saved. 05606 05607 Record.push_back(Data.NumBases); 05608 if (Data.NumBases > 0) 05609 AddCXXBaseSpecifiersRef(Data.getBases(), Data.getBases() + Data.NumBases, 05610 Record); 05611 05612 // FIXME: Make VBases lazily computed when needed to avoid storing them. 05613 Record.push_back(Data.NumVBases); 05614 if (Data.NumVBases > 0) 05615 AddCXXBaseSpecifiersRef(Data.getVBases(), Data.getVBases() + Data.NumVBases, 05616 Record); 05617 05618 AddUnresolvedSet(Data.Conversions.get(*Context), Record); 05619 AddUnresolvedSet(Data.VisibleConversions.get(*Context), Record); 05620 // Data.Definition is the owning decl, no need to write it. 05621 AddDeclRef(D->getFirstFriend(), Record); 05622 05623 // Add lambda-specific data. 05624 if (Data.IsLambda) { 05625 auto &Lambda = D->getLambdaData(); 05626 Record.push_back(Lambda.Dependent); 05627 Record.push_back(Lambda.IsGenericLambda); 05628 Record.push_back(Lambda.CaptureDefault); 05629 Record.push_back(Lambda.NumCaptures); 05630 Record.push_back(Lambda.NumExplicitCaptures); 05631 Record.push_back(Lambda.ManglingNumber); 05632 AddDeclRef(Lambda.ContextDecl, Record); 05633 AddTypeSourceInfo(Lambda.MethodTyInfo, Record); 05634 for (unsigned I = 0, N = Lambda.NumCaptures; I != N; ++I) { 05635 const LambdaCapture &Capture = Lambda.Captures[I]; 05636 AddSourceLocation(Capture.getLocation(), Record); 05637 Record.push_back(Capture.isImplicit()); 05638 Record.push_back(Capture.getCaptureKind()); 05639 switch (Capture.getCaptureKind()) { 05640 case LCK_This: 05641 case LCK_VLAType: 05642 break; 05643 case LCK_ByCopy: 05644 case LCK_ByRef: 05645 VarDecl *Var = 05646 Capture.capturesVariable() ? Capture.getCapturedVar() : nullptr; 05647 AddDeclRef(Var, Record); 05648 AddSourceLocation(Capture.isPackExpansion() ? Capture.getEllipsisLoc() 05649 : SourceLocation(), 05650 Record); 05651 break; 05652 } 05653 } 05654 } 05655 } 05656 05657 void ASTWriter::ReaderInitialized(ASTReader *Reader) { 05658 assert(Reader && "Cannot remove chain"); 05659 assert((!Chain || Chain == Reader) && "Cannot replace chain"); 05660 assert(FirstDeclID == NextDeclID && 05661 FirstTypeID == NextTypeID && 05662 FirstIdentID == NextIdentID && 05663 FirstMacroID == NextMacroID && 05664 FirstSubmoduleID == NextSubmoduleID && 05665 FirstSelectorID == NextSelectorID && 05666 "Setting chain after writing has started."); 05667 05668 Chain = Reader; 05669 05670 FirstDeclID = NUM_PREDEF_DECL_IDS + Chain->getTotalNumDecls(); 05671 FirstTypeID = NUM_PREDEF_TYPE_IDS + Chain->getTotalNumTypes(); 05672 FirstIdentID = NUM_PREDEF_IDENT_IDS + Chain->getTotalNumIdentifiers(); 05673 FirstMacroID = NUM_PREDEF_MACRO_IDS + Chain->getTotalNumMacros(); 05674 FirstSubmoduleID = NUM_PREDEF_SUBMODULE_IDS + Chain->getTotalNumSubmodules(); 05675 FirstSelectorID = NUM_PREDEF_SELECTOR_IDS + Chain->getTotalNumSelectors(); 05676 NextDeclID = FirstDeclID; 05677 NextTypeID = FirstTypeID; 05678 NextIdentID = FirstIdentID; 05679 NextMacroID = FirstMacroID; 05680 NextSelectorID = FirstSelectorID; 05681 NextSubmoduleID = FirstSubmoduleID; 05682 } 05683 05684 void ASTWriter::IdentifierRead(IdentID ID, IdentifierInfo *II) { 05685 // Always keep the highest ID. See \p TypeRead() for more information. 05686 IdentID &StoredID = IdentifierIDs[II]; 05687 if (ID > StoredID) 05688 StoredID = ID; 05689 } 05690 05691 void ASTWriter::MacroRead(serialization::MacroID ID, MacroInfo *MI) { 05692 // Always keep the highest ID. See \p TypeRead() for more information. 05693 MacroID &StoredID = MacroIDs[MI]; 05694 if (ID > StoredID) 05695 StoredID = ID; 05696 } 05697 05698 void ASTWriter::TypeRead(TypeIdx Idx, QualType T) { 05699 // Always take the highest-numbered type index. This copes with an interesting 05700 // case for chained AST writing where we schedule writing the type and then, 05701 // later, deserialize the type from another AST. In this case, we want to 05702 // keep the higher-numbered entry so that we can properly write it out to 05703 // the AST file. 05704 TypeIdx &StoredIdx = TypeIdxs[T]; 05705 if (Idx.getIndex() >= StoredIdx.getIndex()) 05706 StoredIdx = Idx; 05707 } 05708 05709 void ASTWriter::SelectorRead(SelectorID ID, Selector S) { 05710 // Always keep the highest ID. See \p TypeRead() for more information. 05711 SelectorID &StoredID = SelectorIDs[S]; 05712 if (ID > StoredID) 05713 StoredID = ID; 05714 } 05715 05716 void ASTWriter::MacroDefinitionRead(serialization::PreprocessedEntityID ID, 05717 MacroDefinition *MD) { 05718 assert(MacroDefinitions.find(MD) == MacroDefinitions.end()); 05719 MacroDefinitions[MD] = ID; 05720 } 05721 05722 void ASTWriter::ModuleRead(serialization::SubmoduleID ID, Module *Mod) { 05723 assert(SubmoduleIDs.find(Mod) == SubmoduleIDs.end()); 05724 SubmoduleIDs[Mod] = ID; 05725 } 05726 05727 void ASTWriter::CompletedTagDefinition(const TagDecl *D) { 05728 assert(D->isCompleteDefinition()); 05729 assert(!WritingAST && "Already writing the AST!"); 05730 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D)) { 05731 // We are interested when a PCH decl is modified. 05732 if (RD->isFromASTFile()) { 05733 // A forward reference was mutated into a definition. Rewrite it. 05734 // FIXME: This happens during template instantiation, should we 05735 // have created a new definition decl instead ? 05736 assert(isTemplateInstantiation(RD->getTemplateSpecializationKind()) && 05737 "completed a tag from another module but not by instantiation?"); 05738 DeclUpdates[RD].push_back( 05739 DeclUpdate(UPD_CXX_INSTANTIATED_CLASS_DEFINITION)); 05740 } 05741 } 05742 } 05743 05744 void ASTWriter::AddedVisibleDecl(const DeclContext *DC, const Decl *D) { 05745 // TU and namespaces are handled elsewhere. 05746 if (isa<TranslationUnitDecl>(DC) || isa<NamespaceDecl>(DC)) 05747 return; 05748 05749 if (!(!D->isFromASTFile() && cast<Decl>(DC)->isFromASTFile())) 05750 return; // Not a source decl added to a DeclContext from PCH. 05751 05752 assert(!getDefinitiveDeclContext(DC) && "DeclContext not definitive!"); 05753 assert(!WritingAST && "Already writing the AST!"); 05754 AddUpdatedDeclContext(DC); 05755 UpdatingVisibleDecls.push_back(D); 05756 } 05757 05758 void ASTWriter::AddedCXXImplicitMember(const CXXRecordDecl *RD, const Decl *D) { 05759 assert(D->isImplicit()); 05760 if (!(!D->isFromASTFile() && RD->isFromASTFile())) 05761 return; // Not a source member added to a class from PCH. 05762 if (!isa<CXXMethodDecl>(D)) 05763 return; // We are interested in lazily declared implicit methods. 05764 05765 // A decl coming from PCH was modified. 05766 assert(RD->isCompleteDefinition()); 05767 assert(!WritingAST && "Already writing the AST!"); 05768 DeclUpdates[RD].push_back(DeclUpdate(UPD_CXX_ADDED_IMPLICIT_MEMBER, D)); 05769 } 05770 05771 void ASTWriter::AddedCXXTemplateSpecialization(const ClassTemplateDecl *TD, 05772 const ClassTemplateSpecializationDecl *D) { 05773 // The specializations set is kept in the canonical template. 05774 TD = TD->getCanonicalDecl(); 05775 if (!(!D->isFromASTFile() && TD->isFromASTFile())) 05776 return; // Not a source specialization added to a template from PCH. 05777 05778 assert(!WritingAST && "Already writing the AST!"); 05779 DeclUpdates[TD].push_back(DeclUpdate(UPD_CXX_ADDED_TEMPLATE_SPECIALIZATION, 05780 D)); 05781 } 05782 05783 void ASTWriter::AddedCXXTemplateSpecialization( 05784 const VarTemplateDecl *TD, const VarTemplateSpecializationDecl *D) { 05785 // The specializations set is kept in the canonical template. 05786 TD = TD->getCanonicalDecl(); 05787 if (!(!D->isFromASTFile() && TD->isFromASTFile())) 05788 return; // Not a source specialization added to a template from PCH. 05789 05790 assert(!WritingAST && "Already writing the AST!"); 05791 DeclUpdates[TD].push_back(DeclUpdate(UPD_CXX_ADDED_TEMPLATE_SPECIALIZATION, 05792 D)); 05793 } 05794 05795 void ASTWriter::AddedCXXTemplateSpecialization(const FunctionTemplateDecl *TD, 05796 const FunctionDecl *D) { 05797 // The specializations set is kept in the canonical template. 05798 TD = TD->getCanonicalDecl(); 05799 if (!(!D->isFromASTFile() && TD->isFromASTFile())) 05800 return; // Not a source specialization added to a template from PCH. 05801 05802 assert(!WritingAST && "Already writing the AST!"); 05803 DeclUpdates[TD].push_back(DeclUpdate(UPD_CXX_ADDED_TEMPLATE_SPECIALIZATION, 05804 D)); 05805 } 05806 05807 void ASTWriter::ResolvedExceptionSpec(const FunctionDecl *FD) { 05808 assert(!WritingAST && "Already writing the AST!"); 05809 FD = FD->getCanonicalDecl(); 05810 if (!FD->isFromASTFile()) 05811 return; // Not a function declared in PCH and defined outside. 05812 05813 DeclUpdates[FD].push_back(UPD_CXX_RESOLVED_EXCEPTION_SPEC); 05814 } 05815 05816 void ASTWriter::DeducedReturnType(const FunctionDecl *FD, QualType ReturnType) { 05817 assert(!WritingAST && "Already writing the AST!"); 05818 FD = FD->getCanonicalDecl(); 05819 if (!FD->isFromASTFile()) 05820 return; // Not a function declared in PCH and defined outside. 05821 05822 DeclUpdates[FD].push_back(DeclUpdate(UPD_CXX_DEDUCED_RETURN_TYPE, ReturnType)); 05823 } 05824 05825 void ASTWriter::CompletedImplicitDefinition(const FunctionDecl *D) { 05826 assert(!WritingAST && "Already writing the AST!"); 05827 if (!D->isFromASTFile()) 05828 return; // Declaration not imported from PCH. 05829 05830 // Implicit function decl from a PCH was defined. 05831 DeclUpdates[D].push_back(DeclUpdate(UPD_CXX_ADDED_FUNCTION_DEFINITION)); 05832 } 05833 05834 void ASTWriter::FunctionDefinitionInstantiated(const FunctionDecl *D) { 05835 assert(!WritingAST && "Already writing the AST!"); 05836 if (!D->isFromASTFile()) 05837 return; 05838 05839 DeclUpdates[D].push_back( 05840 DeclUpdate(UPD_CXX_ADDED_FUNCTION_DEFINITION)); 05841 } 05842 05843 void ASTWriter::StaticDataMemberInstantiated(const VarDecl *D) { 05844 assert(!WritingAST && "Already writing the AST!"); 05845 if (!D->isFromASTFile()) 05846 return; 05847 05848 // Since the actual instantiation is delayed, this really means that we need 05849 // to update the instantiation location. 05850 DeclUpdates[D].push_back( 05851 DeclUpdate(UPD_CXX_INSTANTIATED_STATIC_DATA_MEMBER, 05852 D->getMemberSpecializationInfo()->getPointOfInstantiation())); 05853 } 05854 05855 void ASTWriter::AddedObjCCategoryToInterface(const ObjCCategoryDecl *CatD, 05856 const ObjCInterfaceDecl *IFD) { 05857 assert(!WritingAST && "Already writing the AST!"); 05858 if (!IFD->isFromASTFile()) 05859 return; // Declaration not imported from PCH. 05860 05861 assert(IFD->getDefinition() && "Category on a class without a definition?"); 05862 ObjCClassesWithCategories.insert( 05863 const_cast<ObjCInterfaceDecl *>(IFD->getDefinition())); 05864 } 05865 05866 05867 void ASTWriter::AddedObjCPropertyInClassExtension(const ObjCPropertyDecl *Prop, 05868 const ObjCPropertyDecl *OrigProp, 05869 const ObjCCategoryDecl *ClassExt) { 05870 const ObjCInterfaceDecl *D = ClassExt->getClassInterface(); 05871 if (!D) 05872 return; 05873 05874 assert(!WritingAST && "Already writing the AST!"); 05875 if (!D->isFromASTFile()) 05876 return; // Declaration not imported from PCH. 05877 05878 RewriteDecl(D); 05879 } 05880 05881 void ASTWriter::DeclarationMarkedUsed(const Decl *D) { 05882 assert(!WritingAST && "Already writing the AST!"); 05883 if (!D->isFromASTFile()) 05884 return; 05885 05886 DeclUpdates[D].push_back(DeclUpdate(UPD_DECL_MARKED_USED)); 05887 } 05888 05889 void ASTWriter::DeclarationMarkedOpenMPThreadPrivate(const Decl *D) { 05890 assert(!WritingAST && "Already writing the AST!"); 05891 if (!D->isFromASTFile()) 05892 return; 05893 05894 DeclUpdates[D].push_back(DeclUpdate(UPD_DECL_MARKED_OPENMP_THREADPRIVATE)); 05895 }