1 //===- ASTImporter.cpp - Importing ASTs from other Contexts ---------------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // This file defines the ASTImporter class which imports AST nodes from one 10 // context into another context. 11 // 12 //===----------------------------------------------------------------------===// 13 14 #include "clang/AST/ASTImporter.h" 15 #include "clang/AST/ASTContext.h" 16 #include "clang/AST/ASTDiagnostic.h" 17 #include "clang/AST/ASTImporterSharedState.h" 18 #include "clang/AST/ASTStructuralEquivalence.h" 19 #include "clang/AST/Attr.h" 20 #include "clang/AST/Decl.h" 21 #include "clang/AST/DeclAccessPair.h" 22 #include "clang/AST/DeclBase.h" 23 #include "clang/AST/DeclCXX.h" 24 #include "clang/AST/DeclFriend.h" 25 #include "clang/AST/DeclGroup.h" 26 #include "clang/AST/DeclObjC.h" 27 #include "clang/AST/DeclTemplate.h" 28 #include "clang/AST/DeclVisitor.h" 29 #include "clang/AST/DeclarationName.h" 30 #include "clang/AST/Expr.h" 31 #include "clang/AST/ExprCXX.h" 32 #include "clang/AST/ExprObjC.h" 33 #include "clang/AST/ExternalASTSource.h" 34 #include "clang/AST/LambdaCapture.h" 35 #include "clang/AST/NestedNameSpecifier.h" 36 #include "clang/AST/OperationKinds.h" 37 #include "clang/AST/Stmt.h" 38 #include "clang/AST/StmtCXX.h" 39 #include "clang/AST/StmtObjC.h" 40 #include "clang/AST/StmtVisitor.h" 41 #include "clang/AST/TemplateBase.h" 42 #include "clang/AST/TemplateName.h" 43 #include "clang/AST/Type.h" 44 #include "clang/AST/TypeLoc.h" 45 #include "clang/AST/TypeVisitor.h" 46 #include "clang/AST/UnresolvedSet.h" 47 #include "clang/Basic/Builtins.h" 48 #include "clang/Basic/ExceptionSpecificationType.h" 49 #include "clang/Basic/FileManager.h" 50 #include "clang/Basic/IdentifierTable.h" 51 #include "clang/Basic/LLVM.h" 52 #include "clang/Basic/LangOptions.h" 53 #include "clang/Basic/SourceLocation.h" 54 #include "clang/Basic/SourceManager.h" 55 #include "clang/Basic/Specifiers.h" 56 #include "llvm/ADT/APSInt.h" 57 #include "llvm/ADT/ArrayRef.h" 58 #include "llvm/ADT/DenseMap.h" 59 #include "llvm/ADT/STLExtras.h" 60 #include "llvm/ADT/ScopeExit.h" 61 #include "llvm/ADT/SmallVector.h" 62 #include "llvm/Support/Casting.h" 63 #include "llvm/Support/ErrorHandling.h" 64 #include "llvm/Support/MemoryBuffer.h" 65 #include <algorithm> 66 #include <cassert> 67 #include <cstddef> 68 #include <memory> 69 #include <optional> 70 #include <type_traits> 71 #include <utility> 72 73 namespace clang { 74 75 using llvm::make_error; 76 using llvm::Error; 77 using llvm::Expected; 78 using ExpectedTypePtr = llvm::Expected<const Type *>; 79 using ExpectedType = llvm::Expected<QualType>; 80 using ExpectedStmt = llvm::Expected<Stmt *>; 81 using ExpectedExpr = llvm::Expected<Expr *>; 82 using ExpectedDecl = llvm::Expected<Decl *>; 83 using ExpectedSLoc = llvm::Expected<SourceLocation>; 84 using ExpectedName = llvm::Expected<DeclarationName>; 85 86 std::string ASTImportError::toString() const { 87 // FIXME: Improve error texts. 88 switch (Error) { 89 case NameConflict: 90 return "NameConflict"; 91 case UnsupportedConstruct: 92 return "UnsupportedConstruct"; 93 case Unknown: 94 return "Unknown error"; 95 } 96 llvm_unreachable("Invalid error code."); 97 return "Invalid error code."; 98 } 99 100 void ASTImportError::log(raw_ostream &OS) const { OS << toString(); } 101 102 std::error_code ASTImportError::convertToErrorCode() const { 103 llvm_unreachable("Function not implemented."); 104 } 105 106 char ASTImportError::ID; 107 108 template <class T> 109 SmallVector<Decl *, 2> 110 getCanonicalForwardRedeclChain(Redeclarable<T>* D) { 111 SmallVector<Decl *, 2> Redecls; 112 for (auto *R : D->getFirstDecl()->redecls()) { 113 if (R != D->getFirstDecl()) 114 Redecls.push_back(R); 115 } 116 Redecls.push_back(D->getFirstDecl()); 117 std::reverse(Redecls.begin(), Redecls.end()); 118 return Redecls; 119 } 120 121 SmallVector<Decl*, 2> getCanonicalForwardRedeclChain(Decl* D) { 122 if (auto *FD = dyn_cast<FunctionDecl>(D)) 123 return getCanonicalForwardRedeclChain<FunctionDecl>(FD); 124 if (auto *VD = dyn_cast<VarDecl>(D)) 125 return getCanonicalForwardRedeclChain<VarDecl>(VD); 126 if (auto *TD = dyn_cast<TagDecl>(D)) 127 return getCanonicalForwardRedeclChain<TagDecl>(TD); 128 llvm_unreachable("Bad declaration kind"); 129 } 130 131 void updateFlags(const Decl *From, Decl *To) { 132 // Check if some flags or attrs are new in 'From' and copy into 'To'. 133 // FIXME: Other flags or attrs? 134 if (From->isUsed(false) && !To->isUsed(false)) 135 To->setIsUsed(); 136 } 137 138 /// How to handle import errors that occur when import of a child declaration 139 /// of a DeclContext fails. 140 class ChildErrorHandlingStrategy { 141 /// This context is imported (in the 'from' domain). 142 /// It is nullptr if a non-DeclContext is imported. 143 const DeclContext *const FromDC; 144 /// Ignore import errors of the children. 145 /// If true, the context can be imported successfully if a child 146 /// of it failed to import. Otherwise the import errors of the child nodes 147 /// are accumulated (joined) into the import error object of the parent. 148 /// (Import of a parent can fail in other ways.) 149 bool const IgnoreChildErrors; 150 151 public: 152 ChildErrorHandlingStrategy(const DeclContext *FromDC) 153 : FromDC(FromDC), IgnoreChildErrors(!isa<TagDecl>(FromDC)) {} 154 ChildErrorHandlingStrategy(const Decl *FromD) 155 : FromDC(dyn_cast<DeclContext>(FromD)), 156 IgnoreChildErrors(!isa<TagDecl>(FromD)) {} 157 158 /// Process the import result of a child (of the current declaration). 159 /// \param ResultErr The import error that can be used as result of 160 /// importing the parent. This may be changed by the function. 161 /// \param ChildErr Result of importing a child. Can be success or error. 162 void handleChildImportResult(Error &ResultErr, Error &&ChildErr) { 163 if (ChildErr && !IgnoreChildErrors) 164 ResultErr = joinErrors(std::move(ResultErr), std::move(ChildErr)); 165 else 166 consumeError(std::move(ChildErr)); 167 } 168 169 /// Determine if import failure of a child does not cause import failure of 170 /// its parent. 171 bool ignoreChildErrorOnParent(Decl *FromChildD) const { 172 if (!IgnoreChildErrors || !FromDC) 173 return false; 174 return FromDC->containsDecl(FromChildD); 175 } 176 }; 177 178 class ASTNodeImporter : public TypeVisitor<ASTNodeImporter, ExpectedType>, 179 public DeclVisitor<ASTNodeImporter, ExpectedDecl>, 180 public StmtVisitor<ASTNodeImporter, ExpectedStmt> { 181 ASTImporter &Importer; 182 183 // Use this instead of Importer.importInto . 184 template <typename ImportT> 185 [[nodiscard]] Error importInto(ImportT &To, const ImportT &From) { 186 return Importer.importInto(To, From); 187 } 188 189 // Use this to import pointers of specific type. 190 template <typename ImportT> 191 [[nodiscard]] Error importInto(ImportT *&To, ImportT *From) { 192 auto ToOrErr = Importer.Import(From); 193 if (ToOrErr) 194 To = cast_or_null<ImportT>(*ToOrErr); 195 return ToOrErr.takeError(); 196 } 197 198 // Call the import function of ASTImporter for a baseclass of type `T` and 199 // cast the return value to `T`. 200 template <typename T> 201 auto import(T *From) 202 -> std::conditional_t<std::is_base_of_v<Type, T>, Expected<const T *>, 203 Expected<T *>> { 204 auto ToOrErr = Importer.Import(From); 205 if (!ToOrErr) 206 return ToOrErr.takeError(); 207 return cast_or_null<T>(*ToOrErr); 208 } 209 210 template <typename T> 211 auto import(const T *From) { 212 return import(const_cast<T *>(From)); 213 } 214 215 // Call the import function of ASTImporter for type `T`. 216 template <typename T> 217 Expected<T> import(const T &From) { 218 return Importer.Import(From); 219 } 220 221 // Import an std::optional<T> by importing the contained T, if any. 222 template <typename T> 223 Expected<std::optional<T>> import(std::optional<T> From) { 224 if (!From) 225 return std::nullopt; 226 return import(*From); 227 } 228 229 ExplicitSpecifier importExplicitSpecifier(Error &Err, 230 ExplicitSpecifier ESpec); 231 232 // Wrapper for an overload set. 233 template <typename ToDeclT> struct CallOverloadedCreateFun { 234 template <typename... Args> decltype(auto) operator()(Args &&... args) { 235 return ToDeclT::Create(std::forward<Args>(args)...); 236 } 237 }; 238 239 // Always use these functions to create a Decl during import. There are 240 // certain tasks which must be done after the Decl was created, e.g. we 241 // must immediately register that as an imported Decl. The parameter `ToD` 242 // will be set to the newly created Decl or if had been imported before 243 // then to the already imported Decl. Returns a bool value set to true if 244 // the `FromD` had been imported before. 245 template <typename ToDeclT, typename FromDeclT, typename... Args> 246 [[nodiscard]] bool GetImportedOrCreateDecl(ToDeclT *&ToD, FromDeclT *FromD, 247 Args &&...args) { 248 // There may be several overloads of ToDeclT::Create. We must make sure 249 // to call the one which would be chosen by the arguments, thus we use a 250 // wrapper for the overload set. 251 CallOverloadedCreateFun<ToDeclT> OC; 252 return GetImportedOrCreateSpecialDecl(ToD, OC, FromD, 253 std::forward<Args>(args)...); 254 } 255 // Use this overload if a special Type is needed to be created. E.g if we 256 // want to create a `TypeAliasDecl` and assign that to a `TypedefNameDecl` 257 // then: 258 // TypedefNameDecl *ToTypedef; 259 // GetImportedOrCreateDecl<TypeAliasDecl>(ToTypedef, FromD, ...); 260 template <typename NewDeclT, typename ToDeclT, typename FromDeclT, 261 typename... Args> 262 [[nodiscard]] bool GetImportedOrCreateDecl(ToDeclT *&ToD, FromDeclT *FromD, 263 Args &&...args) { 264 CallOverloadedCreateFun<NewDeclT> OC; 265 return GetImportedOrCreateSpecialDecl(ToD, OC, FromD, 266 std::forward<Args>(args)...); 267 } 268 // Use this version if a special create function must be 269 // used, e.g. CXXRecordDecl::CreateLambda . 270 template <typename ToDeclT, typename CreateFunT, typename FromDeclT, 271 typename... Args> 272 [[nodiscard]] bool 273 GetImportedOrCreateSpecialDecl(ToDeclT *&ToD, CreateFunT CreateFun, 274 FromDeclT *FromD, Args &&...args) { 275 if (Importer.getImportDeclErrorIfAny(FromD)) { 276 ToD = nullptr; 277 return true; // Already imported but with error. 278 } 279 ToD = cast_or_null<ToDeclT>(Importer.GetAlreadyImportedOrNull(FromD)); 280 if (ToD) 281 return true; // Already imported. 282 ToD = CreateFun(std::forward<Args>(args)...); 283 // Keep track of imported Decls. 284 Importer.RegisterImportedDecl(FromD, ToD); 285 Importer.SharedState->markAsNewDecl(ToD); 286 InitializeImportedDecl(FromD, ToD); 287 return false; // A new Decl is created. 288 } 289 290 void InitializeImportedDecl(Decl *FromD, Decl *ToD) { 291 ToD->IdentifierNamespace = FromD->IdentifierNamespace; 292 if (FromD->isUsed()) 293 ToD->setIsUsed(); 294 if (FromD->isImplicit()) 295 ToD->setImplicit(); 296 } 297 298 // Check if we have found an existing definition. Returns with that 299 // definition if yes, otherwise returns null. 300 Decl *FindAndMapDefinition(FunctionDecl *D, FunctionDecl *FoundFunction) { 301 const FunctionDecl *Definition = nullptr; 302 if (D->doesThisDeclarationHaveABody() && 303 FoundFunction->hasBody(Definition)) 304 return Importer.MapImported(D, const_cast<FunctionDecl *>(Definition)); 305 return nullptr; 306 } 307 308 void addDeclToContexts(Decl *FromD, Decl *ToD) { 309 if (Importer.isMinimalImport()) { 310 // In minimal import case the decl must be added even if it is not 311 // contained in original context, for LLDB compatibility. 312 // FIXME: Check if a better solution is possible. 313 if (!FromD->getDescribedTemplate() && 314 FromD->getFriendObjectKind() == Decl::FOK_None) 315 ToD->getLexicalDeclContext()->addDeclInternal(ToD); 316 return; 317 } 318 319 DeclContext *FromDC = FromD->getDeclContext(); 320 DeclContext *FromLexicalDC = FromD->getLexicalDeclContext(); 321 DeclContext *ToDC = ToD->getDeclContext(); 322 DeclContext *ToLexicalDC = ToD->getLexicalDeclContext(); 323 324 bool Visible = false; 325 if (FromDC->containsDeclAndLoad(FromD)) { 326 ToDC->addDeclInternal(ToD); 327 Visible = true; 328 } 329 if (ToDC != ToLexicalDC && FromLexicalDC->containsDeclAndLoad(FromD)) { 330 ToLexicalDC->addDeclInternal(ToD); 331 Visible = true; 332 } 333 334 // If the Decl was added to any context, it was made already visible. 335 // Otherwise it is still possible that it should be visible. 336 if (!Visible) { 337 if (auto *FromNamed = dyn_cast<NamedDecl>(FromD)) { 338 auto *ToNamed = cast<NamedDecl>(ToD); 339 DeclContextLookupResult FromLookup = 340 FromDC->lookup(FromNamed->getDeclName()); 341 if (llvm::is_contained(FromLookup, FromNamed)) 342 ToDC->makeDeclVisibleInContext(ToNamed); 343 } 344 } 345 } 346 347 void updateLookupTableForTemplateParameters(TemplateParameterList &Params, 348 DeclContext *OldDC) { 349 ASTImporterLookupTable *LT = Importer.SharedState->getLookupTable(); 350 if (!LT) 351 return; 352 353 for (NamedDecl *TP : Params) 354 LT->update(TP, OldDC); 355 } 356 357 void updateLookupTableForTemplateParameters(TemplateParameterList &Params) { 358 updateLookupTableForTemplateParameters( 359 Params, Importer.getToContext().getTranslationUnitDecl()); 360 } 361 362 public: 363 explicit ASTNodeImporter(ASTImporter &Importer) : Importer(Importer) {} 364 365 using TypeVisitor<ASTNodeImporter, ExpectedType>::Visit; 366 using DeclVisitor<ASTNodeImporter, ExpectedDecl>::Visit; 367 using StmtVisitor<ASTNodeImporter, ExpectedStmt>::Visit; 368 369 // Importing types 370 ExpectedType VisitType(const Type *T); 371 ExpectedType VisitAtomicType(const AtomicType *T); 372 ExpectedType VisitBuiltinType(const BuiltinType *T); 373 ExpectedType VisitDecayedType(const DecayedType *T); 374 ExpectedType VisitComplexType(const ComplexType *T); 375 ExpectedType VisitPointerType(const PointerType *T); 376 ExpectedType VisitBlockPointerType(const BlockPointerType *T); 377 ExpectedType VisitLValueReferenceType(const LValueReferenceType *T); 378 ExpectedType VisitRValueReferenceType(const RValueReferenceType *T); 379 ExpectedType VisitMemberPointerType(const MemberPointerType *T); 380 ExpectedType VisitConstantArrayType(const ConstantArrayType *T); 381 ExpectedType VisitIncompleteArrayType(const IncompleteArrayType *T); 382 ExpectedType VisitVariableArrayType(const VariableArrayType *T); 383 ExpectedType VisitDependentSizedArrayType(const DependentSizedArrayType *T); 384 // FIXME: DependentSizedExtVectorType 385 ExpectedType VisitVectorType(const VectorType *T); 386 ExpectedType VisitExtVectorType(const ExtVectorType *T); 387 ExpectedType VisitFunctionNoProtoType(const FunctionNoProtoType *T); 388 ExpectedType VisitFunctionProtoType(const FunctionProtoType *T); 389 ExpectedType VisitUnresolvedUsingType(const UnresolvedUsingType *T); 390 ExpectedType VisitParenType(const ParenType *T); 391 ExpectedType VisitTypedefType(const TypedefType *T); 392 ExpectedType VisitTypeOfExprType(const TypeOfExprType *T); 393 // FIXME: DependentTypeOfExprType 394 ExpectedType VisitTypeOfType(const TypeOfType *T); 395 ExpectedType VisitUsingType(const UsingType *T); 396 ExpectedType VisitDecltypeType(const DecltypeType *T); 397 ExpectedType VisitUnaryTransformType(const UnaryTransformType *T); 398 ExpectedType VisitAutoType(const AutoType *T); 399 ExpectedType VisitDeducedTemplateSpecializationType( 400 const DeducedTemplateSpecializationType *T); 401 ExpectedType VisitInjectedClassNameType(const InjectedClassNameType *T); 402 // FIXME: DependentDecltypeType 403 ExpectedType VisitRecordType(const RecordType *T); 404 ExpectedType VisitEnumType(const EnumType *T); 405 ExpectedType VisitAttributedType(const AttributedType *T); 406 ExpectedType VisitTemplateTypeParmType(const TemplateTypeParmType *T); 407 ExpectedType VisitSubstTemplateTypeParmType( 408 const SubstTemplateTypeParmType *T); 409 ExpectedType 410 VisitSubstTemplateTypeParmPackType(const SubstTemplateTypeParmPackType *T); 411 ExpectedType VisitTemplateSpecializationType( 412 const TemplateSpecializationType *T); 413 ExpectedType VisitElaboratedType(const ElaboratedType *T); 414 ExpectedType VisitDependentNameType(const DependentNameType *T); 415 ExpectedType VisitPackExpansionType(const PackExpansionType *T); 416 ExpectedType VisitDependentTemplateSpecializationType( 417 const DependentTemplateSpecializationType *T); 418 ExpectedType VisitObjCInterfaceType(const ObjCInterfaceType *T); 419 ExpectedType VisitObjCObjectType(const ObjCObjectType *T); 420 ExpectedType VisitObjCObjectPointerType(const ObjCObjectPointerType *T); 421 422 // Importing declarations 423 Error ImportDeclParts(NamedDecl *D, DeclarationName &Name, NamedDecl *&ToD, 424 SourceLocation &Loc); 425 Error ImportDeclParts( 426 NamedDecl *D, DeclContext *&DC, DeclContext *&LexicalDC, 427 DeclarationName &Name, NamedDecl *&ToD, SourceLocation &Loc); 428 Error ImportDefinitionIfNeeded(Decl *FromD, Decl *ToD = nullptr); 429 Error ImportDeclarationNameLoc( 430 const DeclarationNameInfo &From, DeclarationNameInfo &To); 431 Error ImportDeclContext(DeclContext *FromDC, bool ForceImport = false); 432 Error ImportDeclContext( 433 Decl *From, DeclContext *&ToDC, DeclContext *&ToLexicalDC); 434 Error ImportImplicitMethods(const CXXRecordDecl *From, CXXRecordDecl *To); 435 436 Error ImportFieldDeclDefinition(const FieldDecl *From, const FieldDecl *To); 437 Expected<CXXCastPath> ImportCastPath(CastExpr *E); 438 Expected<APValue> ImportAPValue(const APValue &FromValue); 439 440 using Designator = DesignatedInitExpr::Designator; 441 442 /// What we should import from the definition. 443 enum ImportDefinitionKind { 444 /// Import the default subset of the definition, which might be 445 /// nothing (if minimal import is set) or might be everything (if minimal 446 /// import is not set). 447 IDK_Default, 448 /// Import everything. 449 IDK_Everything, 450 /// Import only the bare bones needed to establish a valid 451 /// DeclContext. 452 IDK_Basic 453 }; 454 455 bool shouldForceImportDeclContext(ImportDefinitionKind IDK) { 456 return IDK == IDK_Everything || 457 (IDK == IDK_Default && !Importer.isMinimalImport()); 458 } 459 460 Error ImportInitializer(VarDecl *From, VarDecl *To); 461 Error ImportDefinition( 462 RecordDecl *From, RecordDecl *To, 463 ImportDefinitionKind Kind = IDK_Default); 464 Error ImportDefinition( 465 EnumDecl *From, EnumDecl *To, 466 ImportDefinitionKind Kind = IDK_Default); 467 Error ImportDefinition( 468 ObjCInterfaceDecl *From, ObjCInterfaceDecl *To, 469 ImportDefinitionKind Kind = IDK_Default); 470 Error ImportDefinition( 471 ObjCProtocolDecl *From, ObjCProtocolDecl *To, 472 ImportDefinitionKind Kind = IDK_Default); 473 Error ImportTemplateArguments(ArrayRef<TemplateArgument> FromArgs, 474 SmallVectorImpl<TemplateArgument> &ToArgs); 475 Expected<TemplateArgument> 476 ImportTemplateArgument(const TemplateArgument &From); 477 478 template <typename InContainerTy> 479 Error ImportTemplateArgumentListInfo( 480 const InContainerTy &Container, TemplateArgumentListInfo &ToTAInfo); 481 482 template<typename InContainerTy> 483 Error ImportTemplateArgumentListInfo( 484 SourceLocation FromLAngleLoc, SourceLocation FromRAngleLoc, 485 const InContainerTy &Container, TemplateArgumentListInfo &Result); 486 487 using TemplateArgsTy = SmallVector<TemplateArgument, 8>; 488 using FunctionTemplateAndArgsTy = 489 std::tuple<FunctionTemplateDecl *, TemplateArgsTy>; 490 Expected<FunctionTemplateAndArgsTy> 491 ImportFunctionTemplateWithTemplateArgsFromSpecialization( 492 FunctionDecl *FromFD); 493 Error ImportTemplateParameterLists(const DeclaratorDecl *FromD, 494 DeclaratorDecl *ToD); 495 496 Error ImportTemplateInformation(FunctionDecl *FromFD, FunctionDecl *ToFD); 497 498 Error ImportFunctionDeclBody(FunctionDecl *FromFD, FunctionDecl *ToFD); 499 500 Error ImportDefaultArgOfParmVarDecl(const ParmVarDecl *FromParam, 501 ParmVarDecl *ToParam); 502 503 Expected<InheritedConstructor> 504 ImportInheritedConstructor(const InheritedConstructor &From); 505 506 template <typename T> 507 bool hasSameVisibilityContextAndLinkage(T *Found, T *From); 508 509 bool IsStructuralMatch(Decl *From, Decl *To, bool Complain = true); 510 ExpectedDecl VisitDecl(Decl *D); 511 ExpectedDecl VisitImportDecl(ImportDecl *D); 512 ExpectedDecl VisitEmptyDecl(EmptyDecl *D); 513 ExpectedDecl VisitAccessSpecDecl(AccessSpecDecl *D); 514 ExpectedDecl VisitStaticAssertDecl(StaticAssertDecl *D); 515 ExpectedDecl VisitTranslationUnitDecl(TranslationUnitDecl *D); 516 ExpectedDecl VisitBindingDecl(BindingDecl *D); 517 ExpectedDecl VisitNamespaceDecl(NamespaceDecl *D); 518 ExpectedDecl VisitNamespaceAliasDecl(NamespaceAliasDecl *D); 519 ExpectedDecl VisitTypedefNameDecl(TypedefNameDecl *D, bool IsAlias); 520 ExpectedDecl VisitTypedefDecl(TypedefDecl *D); 521 ExpectedDecl VisitTypeAliasDecl(TypeAliasDecl *D); 522 ExpectedDecl VisitTypeAliasTemplateDecl(TypeAliasTemplateDecl *D); 523 ExpectedDecl VisitLabelDecl(LabelDecl *D); 524 ExpectedDecl VisitEnumDecl(EnumDecl *D); 525 ExpectedDecl VisitRecordDecl(RecordDecl *D); 526 ExpectedDecl VisitEnumConstantDecl(EnumConstantDecl *D); 527 ExpectedDecl VisitFunctionDecl(FunctionDecl *D); 528 ExpectedDecl VisitCXXMethodDecl(CXXMethodDecl *D); 529 ExpectedDecl VisitCXXConstructorDecl(CXXConstructorDecl *D); 530 ExpectedDecl VisitCXXDestructorDecl(CXXDestructorDecl *D); 531 ExpectedDecl VisitCXXConversionDecl(CXXConversionDecl *D); 532 ExpectedDecl VisitCXXDeductionGuideDecl(CXXDeductionGuideDecl *D); 533 ExpectedDecl VisitFieldDecl(FieldDecl *D); 534 ExpectedDecl VisitIndirectFieldDecl(IndirectFieldDecl *D); 535 ExpectedDecl VisitFriendDecl(FriendDecl *D); 536 ExpectedDecl VisitObjCIvarDecl(ObjCIvarDecl *D); 537 ExpectedDecl VisitVarDecl(VarDecl *D); 538 ExpectedDecl VisitImplicitParamDecl(ImplicitParamDecl *D); 539 ExpectedDecl VisitParmVarDecl(ParmVarDecl *D); 540 ExpectedDecl VisitObjCMethodDecl(ObjCMethodDecl *D); 541 ExpectedDecl VisitObjCTypeParamDecl(ObjCTypeParamDecl *D); 542 ExpectedDecl VisitObjCCategoryDecl(ObjCCategoryDecl *D); 543 ExpectedDecl VisitObjCProtocolDecl(ObjCProtocolDecl *D); 544 ExpectedDecl VisitLinkageSpecDecl(LinkageSpecDecl *D); 545 ExpectedDecl VisitUsingDecl(UsingDecl *D); 546 ExpectedDecl VisitUsingShadowDecl(UsingShadowDecl *D); 547 ExpectedDecl VisitUsingDirectiveDecl(UsingDirectiveDecl *D); 548 ExpectedDecl VisitUsingPackDecl(UsingPackDecl *D); 549 ExpectedDecl ImportUsingShadowDecls(BaseUsingDecl *D, BaseUsingDecl *ToSI); 550 ExpectedDecl VisitUsingEnumDecl(UsingEnumDecl *D); 551 ExpectedDecl VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D); 552 ExpectedDecl VisitUnresolvedUsingTypenameDecl(UnresolvedUsingTypenameDecl *D); 553 ExpectedDecl VisitBuiltinTemplateDecl(BuiltinTemplateDecl *D); 554 ExpectedDecl 555 VisitLifetimeExtendedTemporaryDecl(LifetimeExtendedTemporaryDecl *D); 556 557 Expected<ObjCTypeParamList *> 558 ImportObjCTypeParamList(ObjCTypeParamList *list); 559 560 ExpectedDecl VisitObjCInterfaceDecl(ObjCInterfaceDecl *D); 561 ExpectedDecl VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D); 562 ExpectedDecl VisitObjCImplementationDecl(ObjCImplementationDecl *D); 563 ExpectedDecl VisitObjCPropertyDecl(ObjCPropertyDecl *D); 564 ExpectedDecl VisitObjCPropertyImplDecl(ObjCPropertyImplDecl *D); 565 ExpectedDecl VisitTemplateTypeParmDecl(TemplateTypeParmDecl *D); 566 ExpectedDecl VisitNonTypeTemplateParmDecl(NonTypeTemplateParmDecl *D); 567 ExpectedDecl VisitTemplateTemplateParmDecl(TemplateTemplateParmDecl *D); 568 ExpectedDecl VisitClassTemplateDecl(ClassTemplateDecl *D); 569 ExpectedDecl VisitClassTemplateSpecializationDecl( 570 ClassTemplateSpecializationDecl *D); 571 ExpectedDecl VisitVarTemplateDecl(VarTemplateDecl *D); 572 ExpectedDecl VisitVarTemplateSpecializationDecl(VarTemplateSpecializationDecl *D); 573 ExpectedDecl VisitFunctionTemplateDecl(FunctionTemplateDecl *D); 574 575 // Importing statements 576 ExpectedStmt VisitStmt(Stmt *S); 577 ExpectedStmt VisitGCCAsmStmt(GCCAsmStmt *S); 578 ExpectedStmt VisitDeclStmt(DeclStmt *S); 579 ExpectedStmt VisitNullStmt(NullStmt *S); 580 ExpectedStmt VisitCompoundStmt(CompoundStmt *S); 581 ExpectedStmt VisitCaseStmt(CaseStmt *S); 582 ExpectedStmt VisitDefaultStmt(DefaultStmt *S); 583 ExpectedStmt VisitLabelStmt(LabelStmt *S); 584 ExpectedStmt VisitAttributedStmt(AttributedStmt *S); 585 ExpectedStmt VisitIfStmt(IfStmt *S); 586 ExpectedStmt VisitSwitchStmt(SwitchStmt *S); 587 ExpectedStmt VisitWhileStmt(WhileStmt *S); 588 ExpectedStmt VisitDoStmt(DoStmt *S); 589 ExpectedStmt VisitForStmt(ForStmt *S); 590 ExpectedStmt VisitGotoStmt(GotoStmt *S); 591 ExpectedStmt VisitIndirectGotoStmt(IndirectGotoStmt *S); 592 ExpectedStmt VisitContinueStmt(ContinueStmt *S); 593 ExpectedStmt VisitBreakStmt(BreakStmt *S); 594 ExpectedStmt VisitReturnStmt(ReturnStmt *S); 595 // FIXME: MSAsmStmt 596 // FIXME: SEHExceptStmt 597 // FIXME: SEHFinallyStmt 598 // FIXME: SEHTryStmt 599 // FIXME: SEHLeaveStmt 600 // FIXME: CapturedStmt 601 ExpectedStmt VisitCXXCatchStmt(CXXCatchStmt *S); 602 ExpectedStmt VisitCXXTryStmt(CXXTryStmt *S); 603 ExpectedStmt VisitCXXForRangeStmt(CXXForRangeStmt *S); 604 // FIXME: MSDependentExistsStmt 605 ExpectedStmt VisitObjCForCollectionStmt(ObjCForCollectionStmt *S); 606 ExpectedStmt VisitObjCAtCatchStmt(ObjCAtCatchStmt *S); 607 ExpectedStmt VisitObjCAtFinallyStmt(ObjCAtFinallyStmt *S); 608 ExpectedStmt VisitObjCAtTryStmt(ObjCAtTryStmt *S); 609 ExpectedStmt VisitObjCAtSynchronizedStmt(ObjCAtSynchronizedStmt *S); 610 ExpectedStmt VisitObjCAtThrowStmt(ObjCAtThrowStmt *S); 611 ExpectedStmt VisitObjCAutoreleasePoolStmt(ObjCAutoreleasePoolStmt *S); 612 613 // Importing expressions 614 ExpectedStmt VisitExpr(Expr *E); 615 ExpectedStmt VisitSourceLocExpr(SourceLocExpr *E); 616 ExpectedStmt VisitVAArgExpr(VAArgExpr *E); 617 ExpectedStmt VisitChooseExpr(ChooseExpr *E); 618 ExpectedStmt VisitShuffleVectorExpr(ShuffleVectorExpr *E); 619 ExpectedStmt VisitGNUNullExpr(GNUNullExpr *E); 620 ExpectedStmt VisitGenericSelectionExpr(GenericSelectionExpr *E); 621 ExpectedStmt VisitPredefinedExpr(PredefinedExpr *E); 622 ExpectedStmt VisitDeclRefExpr(DeclRefExpr *E); 623 ExpectedStmt VisitImplicitValueInitExpr(ImplicitValueInitExpr *E); 624 ExpectedStmt VisitDesignatedInitExpr(DesignatedInitExpr *E); 625 ExpectedStmt VisitCXXNullPtrLiteralExpr(CXXNullPtrLiteralExpr *E); 626 ExpectedStmt VisitIntegerLiteral(IntegerLiteral *E); 627 ExpectedStmt VisitFloatingLiteral(FloatingLiteral *E); 628 ExpectedStmt VisitImaginaryLiteral(ImaginaryLiteral *E); 629 ExpectedStmt VisitFixedPointLiteral(FixedPointLiteral *E); 630 ExpectedStmt VisitCharacterLiteral(CharacterLiteral *E); 631 ExpectedStmt VisitStringLiteral(StringLiteral *E); 632 ExpectedStmt VisitCompoundLiteralExpr(CompoundLiteralExpr *E); 633 ExpectedStmt VisitAtomicExpr(AtomicExpr *E); 634 ExpectedStmt VisitAddrLabelExpr(AddrLabelExpr *E); 635 ExpectedStmt VisitConstantExpr(ConstantExpr *E); 636 ExpectedStmt VisitParenExpr(ParenExpr *E); 637 ExpectedStmt VisitParenListExpr(ParenListExpr *E); 638 ExpectedStmt VisitStmtExpr(StmtExpr *E); 639 ExpectedStmt VisitUnaryOperator(UnaryOperator *E); 640 ExpectedStmt VisitUnaryExprOrTypeTraitExpr(UnaryExprOrTypeTraitExpr *E); 641 ExpectedStmt VisitBinaryOperator(BinaryOperator *E); 642 ExpectedStmt VisitConditionalOperator(ConditionalOperator *E); 643 ExpectedStmt VisitBinaryConditionalOperator(BinaryConditionalOperator *E); 644 ExpectedStmt VisitCXXRewrittenBinaryOperator(CXXRewrittenBinaryOperator *E); 645 ExpectedStmt VisitOpaqueValueExpr(OpaqueValueExpr *E); 646 ExpectedStmt VisitArrayTypeTraitExpr(ArrayTypeTraitExpr *E); 647 ExpectedStmt VisitExpressionTraitExpr(ExpressionTraitExpr *E); 648 ExpectedStmt VisitArraySubscriptExpr(ArraySubscriptExpr *E); 649 ExpectedStmt VisitCompoundAssignOperator(CompoundAssignOperator *E); 650 ExpectedStmt VisitImplicitCastExpr(ImplicitCastExpr *E); 651 ExpectedStmt VisitExplicitCastExpr(ExplicitCastExpr *E); 652 ExpectedStmt VisitOffsetOfExpr(OffsetOfExpr *OE); 653 ExpectedStmt VisitCXXThrowExpr(CXXThrowExpr *E); 654 ExpectedStmt VisitCXXNoexceptExpr(CXXNoexceptExpr *E); 655 ExpectedStmt VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E); 656 ExpectedStmt VisitCXXScalarValueInitExpr(CXXScalarValueInitExpr *E); 657 ExpectedStmt VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E); 658 ExpectedStmt VisitCXXTemporaryObjectExpr(CXXTemporaryObjectExpr *E); 659 ExpectedStmt VisitMaterializeTemporaryExpr(MaterializeTemporaryExpr *E); 660 ExpectedStmt VisitPackExpansionExpr(PackExpansionExpr *E); 661 ExpectedStmt VisitSizeOfPackExpr(SizeOfPackExpr *E); 662 ExpectedStmt VisitCXXNewExpr(CXXNewExpr *E); 663 ExpectedStmt VisitCXXDeleteExpr(CXXDeleteExpr *E); 664 ExpectedStmt VisitCXXConstructExpr(CXXConstructExpr *E); 665 ExpectedStmt VisitCXXMemberCallExpr(CXXMemberCallExpr *E); 666 ExpectedStmt VisitCXXDependentScopeMemberExpr(CXXDependentScopeMemberExpr *E); 667 ExpectedStmt VisitDependentScopeDeclRefExpr(DependentScopeDeclRefExpr *E); 668 ExpectedStmt VisitCXXUnresolvedConstructExpr(CXXUnresolvedConstructExpr *E); 669 ExpectedStmt VisitUnresolvedLookupExpr(UnresolvedLookupExpr *E); 670 ExpectedStmt VisitUnresolvedMemberExpr(UnresolvedMemberExpr *E); 671 ExpectedStmt VisitExprWithCleanups(ExprWithCleanups *E); 672 ExpectedStmt VisitCXXThisExpr(CXXThisExpr *E); 673 ExpectedStmt VisitCXXBoolLiteralExpr(CXXBoolLiteralExpr *E); 674 ExpectedStmt VisitCXXPseudoDestructorExpr(CXXPseudoDestructorExpr *E); 675 ExpectedStmt VisitMemberExpr(MemberExpr *E); 676 ExpectedStmt VisitCallExpr(CallExpr *E); 677 ExpectedStmt VisitLambdaExpr(LambdaExpr *LE); 678 ExpectedStmt VisitInitListExpr(InitListExpr *E); 679 ExpectedStmt VisitCXXStdInitializerListExpr(CXXStdInitializerListExpr *E); 680 ExpectedStmt VisitCXXInheritedCtorInitExpr(CXXInheritedCtorInitExpr *E); 681 ExpectedStmt VisitArrayInitLoopExpr(ArrayInitLoopExpr *E); 682 ExpectedStmt VisitArrayInitIndexExpr(ArrayInitIndexExpr *E); 683 ExpectedStmt VisitCXXDefaultInitExpr(CXXDefaultInitExpr *E); 684 ExpectedStmt VisitCXXNamedCastExpr(CXXNamedCastExpr *E); 685 ExpectedStmt VisitSubstNonTypeTemplateParmExpr(SubstNonTypeTemplateParmExpr *E); 686 ExpectedStmt VisitTypeTraitExpr(TypeTraitExpr *E); 687 ExpectedStmt VisitCXXTypeidExpr(CXXTypeidExpr *E); 688 ExpectedStmt VisitCXXFoldExpr(CXXFoldExpr *E); 689 690 // Helper for chaining together multiple imports. If an error is detected, 691 // subsequent imports will return default constructed nodes, so that failure 692 // can be detected with a single conditional branch after a sequence of 693 // imports. 694 template <typename T> T importChecked(Error &Err, const T &From) { 695 // Don't attempt to import nodes if we hit an error earlier. 696 if (Err) 697 return T{}; 698 Expected<T> MaybeVal = import(From); 699 if (!MaybeVal) { 700 Err = MaybeVal.takeError(); 701 return T{}; 702 } 703 return *MaybeVal; 704 } 705 706 template<typename IIter, typename OIter> 707 Error ImportArrayChecked(IIter Ibegin, IIter Iend, OIter Obegin) { 708 using ItemT = std::remove_reference_t<decltype(*Obegin)>; 709 for (; Ibegin != Iend; ++Ibegin, ++Obegin) { 710 Expected<ItemT> ToOrErr = import(*Ibegin); 711 if (!ToOrErr) 712 return ToOrErr.takeError(); 713 *Obegin = *ToOrErr; 714 } 715 return Error::success(); 716 } 717 718 // Import every item from a container structure into an output container. 719 // If error occurs, stops at first error and returns the error. 720 // The output container should have space for all needed elements (it is not 721 // expanded, new items are put into from the beginning). 722 template<typename InContainerTy, typename OutContainerTy> 723 Error ImportContainerChecked( 724 const InContainerTy &InContainer, OutContainerTy &OutContainer) { 725 return ImportArrayChecked( 726 InContainer.begin(), InContainer.end(), OutContainer.begin()); 727 } 728 729 template<typename InContainerTy, typename OIter> 730 Error ImportArrayChecked(const InContainerTy &InContainer, OIter Obegin) { 731 return ImportArrayChecked(InContainer.begin(), InContainer.end(), Obegin); 732 } 733 734 Error ImportOverriddenMethods(CXXMethodDecl *ToMethod, 735 CXXMethodDecl *FromMethod); 736 737 Expected<FunctionDecl *> FindFunctionTemplateSpecialization( 738 FunctionDecl *FromFD); 739 740 // Returns true if the given function has a placeholder return type and 741 // that type is declared inside the body of the function. 742 // E.g. auto f() { struct X{}; return X(); } 743 bool hasAutoReturnTypeDeclaredInside(FunctionDecl *D); 744 }; 745 746 template <typename InContainerTy> 747 Error ASTNodeImporter::ImportTemplateArgumentListInfo( 748 SourceLocation FromLAngleLoc, SourceLocation FromRAngleLoc, 749 const InContainerTy &Container, TemplateArgumentListInfo &Result) { 750 auto ToLAngleLocOrErr = import(FromLAngleLoc); 751 if (!ToLAngleLocOrErr) 752 return ToLAngleLocOrErr.takeError(); 753 auto ToRAngleLocOrErr = import(FromRAngleLoc); 754 if (!ToRAngleLocOrErr) 755 return ToRAngleLocOrErr.takeError(); 756 757 TemplateArgumentListInfo ToTAInfo(*ToLAngleLocOrErr, *ToRAngleLocOrErr); 758 if (auto Err = ImportTemplateArgumentListInfo(Container, ToTAInfo)) 759 return Err; 760 Result = ToTAInfo; 761 return Error::success(); 762 } 763 764 template <> 765 Error ASTNodeImporter::ImportTemplateArgumentListInfo<TemplateArgumentListInfo>( 766 const TemplateArgumentListInfo &From, TemplateArgumentListInfo &Result) { 767 return ImportTemplateArgumentListInfo( 768 From.getLAngleLoc(), From.getRAngleLoc(), From.arguments(), Result); 769 } 770 771 template <> 772 Error ASTNodeImporter::ImportTemplateArgumentListInfo< 773 ASTTemplateArgumentListInfo>( 774 const ASTTemplateArgumentListInfo &From, 775 TemplateArgumentListInfo &Result) { 776 return ImportTemplateArgumentListInfo( 777 From.LAngleLoc, From.RAngleLoc, From.arguments(), Result); 778 } 779 780 Expected<ASTNodeImporter::FunctionTemplateAndArgsTy> 781 ASTNodeImporter::ImportFunctionTemplateWithTemplateArgsFromSpecialization( 782 FunctionDecl *FromFD) { 783 assert(FromFD->getTemplatedKind() == 784 FunctionDecl::TK_FunctionTemplateSpecialization); 785 786 FunctionTemplateAndArgsTy Result; 787 788 auto *FTSInfo = FromFD->getTemplateSpecializationInfo(); 789 if (Error Err = importInto(std::get<0>(Result), FTSInfo->getTemplate())) 790 return std::move(Err); 791 792 // Import template arguments. 793 if (Error Err = ImportTemplateArguments(FTSInfo->TemplateArguments->asArray(), 794 std::get<1>(Result))) 795 return std::move(Err); 796 797 return Result; 798 } 799 800 template <> 801 Expected<TemplateParameterList *> 802 ASTNodeImporter::import(TemplateParameterList *From) { 803 SmallVector<NamedDecl *, 4> To(From->size()); 804 if (Error Err = ImportContainerChecked(*From, To)) 805 return std::move(Err); 806 807 ExpectedExpr ToRequiresClause = import(From->getRequiresClause()); 808 if (!ToRequiresClause) 809 return ToRequiresClause.takeError(); 810 811 auto ToTemplateLocOrErr = import(From->getTemplateLoc()); 812 if (!ToTemplateLocOrErr) 813 return ToTemplateLocOrErr.takeError(); 814 auto ToLAngleLocOrErr = import(From->getLAngleLoc()); 815 if (!ToLAngleLocOrErr) 816 return ToLAngleLocOrErr.takeError(); 817 auto ToRAngleLocOrErr = import(From->getRAngleLoc()); 818 if (!ToRAngleLocOrErr) 819 return ToRAngleLocOrErr.takeError(); 820 821 return TemplateParameterList::Create( 822 Importer.getToContext(), 823 *ToTemplateLocOrErr, 824 *ToLAngleLocOrErr, 825 To, 826 *ToRAngleLocOrErr, 827 *ToRequiresClause); 828 } 829 830 template <> 831 Expected<TemplateArgument> 832 ASTNodeImporter::import(const TemplateArgument &From) { 833 switch (From.getKind()) { 834 case TemplateArgument::Null: 835 return TemplateArgument(); 836 837 case TemplateArgument::Type: { 838 ExpectedType ToTypeOrErr = import(From.getAsType()); 839 if (!ToTypeOrErr) 840 return ToTypeOrErr.takeError(); 841 return TemplateArgument(*ToTypeOrErr, /*isNullPtr*/ false, 842 From.getIsDefaulted()); 843 } 844 845 case TemplateArgument::Integral: { 846 ExpectedType ToTypeOrErr = import(From.getIntegralType()); 847 if (!ToTypeOrErr) 848 return ToTypeOrErr.takeError(); 849 return TemplateArgument(From, *ToTypeOrErr); 850 } 851 852 case TemplateArgument::Declaration: { 853 Expected<ValueDecl *> ToOrErr = import(From.getAsDecl()); 854 if (!ToOrErr) 855 return ToOrErr.takeError(); 856 ExpectedType ToTypeOrErr = import(From.getParamTypeForDecl()); 857 if (!ToTypeOrErr) 858 return ToTypeOrErr.takeError(); 859 return TemplateArgument(*ToOrErr, *ToTypeOrErr, From.getIsDefaulted()); 860 } 861 862 case TemplateArgument::NullPtr: { 863 ExpectedType ToTypeOrErr = import(From.getNullPtrType()); 864 if (!ToTypeOrErr) 865 return ToTypeOrErr.takeError(); 866 return TemplateArgument(*ToTypeOrErr, /*isNullPtr*/ true, 867 From.getIsDefaulted()); 868 } 869 870 case TemplateArgument::Template: { 871 Expected<TemplateName> ToTemplateOrErr = import(From.getAsTemplate()); 872 if (!ToTemplateOrErr) 873 return ToTemplateOrErr.takeError(); 874 875 return TemplateArgument(*ToTemplateOrErr, From.getIsDefaulted()); 876 } 877 878 case TemplateArgument::TemplateExpansion: { 879 Expected<TemplateName> ToTemplateOrErr = 880 import(From.getAsTemplateOrTemplatePattern()); 881 if (!ToTemplateOrErr) 882 return ToTemplateOrErr.takeError(); 883 884 return TemplateArgument(*ToTemplateOrErr, From.getNumTemplateExpansions(), 885 From.getIsDefaulted()); 886 } 887 888 case TemplateArgument::Expression: 889 if (ExpectedExpr ToExpr = import(From.getAsExpr())) 890 return TemplateArgument(*ToExpr, From.getIsDefaulted()); 891 else 892 return ToExpr.takeError(); 893 894 case TemplateArgument::Pack: { 895 SmallVector<TemplateArgument, 2> ToPack; 896 ToPack.reserve(From.pack_size()); 897 if (Error Err = ImportTemplateArguments(From.pack_elements(), ToPack)) 898 return std::move(Err); 899 900 return TemplateArgument( 901 llvm::ArrayRef(ToPack).copy(Importer.getToContext())); 902 } 903 } 904 905 llvm_unreachable("Invalid template argument kind"); 906 } 907 908 template <> 909 Expected<TemplateArgumentLoc> 910 ASTNodeImporter::import(const TemplateArgumentLoc &TALoc) { 911 Expected<TemplateArgument> ArgOrErr = import(TALoc.getArgument()); 912 if (!ArgOrErr) 913 return ArgOrErr.takeError(); 914 TemplateArgument Arg = *ArgOrErr; 915 916 TemplateArgumentLocInfo FromInfo = TALoc.getLocInfo(); 917 918 TemplateArgumentLocInfo ToInfo; 919 if (Arg.getKind() == TemplateArgument::Expression) { 920 ExpectedExpr E = import(FromInfo.getAsExpr()); 921 if (!E) 922 return E.takeError(); 923 ToInfo = TemplateArgumentLocInfo(*E); 924 } else if (Arg.getKind() == TemplateArgument::Type) { 925 if (auto TSIOrErr = import(FromInfo.getAsTypeSourceInfo())) 926 ToInfo = TemplateArgumentLocInfo(*TSIOrErr); 927 else 928 return TSIOrErr.takeError(); 929 } else { 930 auto ToTemplateQualifierLocOrErr = 931 import(FromInfo.getTemplateQualifierLoc()); 932 if (!ToTemplateQualifierLocOrErr) 933 return ToTemplateQualifierLocOrErr.takeError(); 934 auto ToTemplateNameLocOrErr = import(FromInfo.getTemplateNameLoc()); 935 if (!ToTemplateNameLocOrErr) 936 return ToTemplateNameLocOrErr.takeError(); 937 auto ToTemplateEllipsisLocOrErr = 938 import(FromInfo.getTemplateEllipsisLoc()); 939 if (!ToTemplateEllipsisLocOrErr) 940 return ToTemplateEllipsisLocOrErr.takeError(); 941 ToInfo = TemplateArgumentLocInfo( 942 Importer.getToContext(), *ToTemplateQualifierLocOrErr, 943 *ToTemplateNameLocOrErr, *ToTemplateEllipsisLocOrErr); 944 } 945 946 return TemplateArgumentLoc(Arg, ToInfo); 947 } 948 949 template <> 950 Expected<DeclGroupRef> ASTNodeImporter::import(const DeclGroupRef &DG) { 951 if (DG.isNull()) 952 return DeclGroupRef::Create(Importer.getToContext(), nullptr, 0); 953 size_t NumDecls = DG.end() - DG.begin(); 954 SmallVector<Decl *, 1> ToDecls; 955 ToDecls.reserve(NumDecls); 956 for (Decl *FromD : DG) { 957 if (auto ToDOrErr = import(FromD)) 958 ToDecls.push_back(*ToDOrErr); 959 else 960 return ToDOrErr.takeError(); 961 } 962 return DeclGroupRef::Create(Importer.getToContext(), 963 ToDecls.begin(), 964 NumDecls); 965 } 966 967 template <> 968 Expected<ASTNodeImporter::Designator> 969 ASTNodeImporter::import(const Designator &D) { 970 if (D.isFieldDesignator()) { 971 IdentifierInfo *ToFieldName = Importer.Import(D.getFieldName()); 972 973 ExpectedSLoc ToDotLocOrErr = import(D.getDotLoc()); 974 if (!ToDotLocOrErr) 975 return ToDotLocOrErr.takeError(); 976 977 ExpectedSLoc ToFieldLocOrErr = import(D.getFieldLoc()); 978 if (!ToFieldLocOrErr) 979 return ToFieldLocOrErr.takeError(); 980 981 return DesignatedInitExpr::Designator::CreateFieldDesignator( 982 ToFieldName, *ToDotLocOrErr, *ToFieldLocOrErr); 983 } 984 985 ExpectedSLoc ToLBracketLocOrErr = import(D.getLBracketLoc()); 986 if (!ToLBracketLocOrErr) 987 return ToLBracketLocOrErr.takeError(); 988 989 ExpectedSLoc ToRBracketLocOrErr = import(D.getRBracketLoc()); 990 if (!ToRBracketLocOrErr) 991 return ToRBracketLocOrErr.takeError(); 992 993 if (D.isArrayDesignator()) 994 return Designator::CreateArrayDesignator(D.getArrayIndex(), 995 *ToLBracketLocOrErr, 996 *ToRBracketLocOrErr); 997 998 ExpectedSLoc ToEllipsisLocOrErr = import(D.getEllipsisLoc()); 999 if (!ToEllipsisLocOrErr) 1000 return ToEllipsisLocOrErr.takeError(); 1001 1002 assert(D.isArrayRangeDesignator()); 1003 return Designator::CreateArrayRangeDesignator( 1004 D.getArrayIndex(), *ToLBracketLocOrErr, *ToEllipsisLocOrErr, 1005 *ToRBracketLocOrErr); 1006 } 1007 1008 template <> 1009 Expected<LambdaCapture> ASTNodeImporter::import(const LambdaCapture &From) { 1010 ValueDecl *Var = nullptr; 1011 if (From.capturesVariable()) { 1012 if (auto VarOrErr = import(From.getCapturedVar())) 1013 Var = *VarOrErr; 1014 else 1015 return VarOrErr.takeError(); 1016 } 1017 1018 auto LocationOrErr = import(From.getLocation()); 1019 if (!LocationOrErr) 1020 return LocationOrErr.takeError(); 1021 1022 SourceLocation EllipsisLoc; 1023 if (From.isPackExpansion()) 1024 if (Error Err = importInto(EllipsisLoc, From.getEllipsisLoc())) 1025 return std::move(Err); 1026 1027 return LambdaCapture( 1028 *LocationOrErr, From.isImplicit(), From.getCaptureKind(), Var, 1029 EllipsisLoc); 1030 } 1031 1032 template <typename T> 1033 bool ASTNodeImporter::hasSameVisibilityContextAndLinkage(T *Found, T *From) { 1034 if (Found->getLinkageInternal() != From->getLinkageInternal()) 1035 return false; 1036 1037 if (From->hasExternalFormalLinkage()) 1038 return Found->hasExternalFormalLinkage(); 1039 if (Importer.GetFromTU(Found) != From->getTranslationUnitDecl()) 1040 return false; 1041 if (From->isInAnonymousNamespace()) 1042 return Found->isInAnonymousNamespace(); 1043 else 1044 return !Found->isInAnonymousNamespace() && 1045 !Found->hasExternalFormalLinkage(); 1046 } 1047 1048 template <> 1049 bool ASTNodeImporter::hasSameVisibilityContextAndLinkage(TypedefNameDecl *Found, 1050 TypedefNameDecl *From) { 1051 if (Found->getLinkageInternal() != From->getLinkageInternal()) 1052 return false; 1053 1054 if (From->isInAnonymousNamespace() && Found->isInAnonymousNamespace()) 1055 return Importer.GetFromTU(Found) == From->getTranslationUnitDecl(); 1056 return From->isInAnonymousNamespace() == Found->isInAnonymousNamespace(); 1057 } 1058 1059 } // namespace clang 1060 1061 //---------------------------------------------------------------------------- 1062 // Import Types 1063 //---------------------------------------------------------------------------- 1064 1065 using namespace clang; 1066 1067 ExpectedType ASTNodeImporter::VisitType(const Type *T) { 1068 Importer.FromDiag(SourceLocation(), diag::err_unsupported_ast_node) 1069 << T->getTypeClassName(); 1070 return make_error<ASTImportError>(ASTImportError::UnsupportedConstruct); 1071 } 1072 1073 ExpectedType ASTNodeImporter::VisitAtomicType(const AtomicType *T){ 1074 ExpectedType UnderlyingTypeOrErr = import(T->getValueType()); 1075 if (!UnderlyingTypeOrErr) 1076 return UnderlyingTypeOrErr.takeError(); 1077 1078 return Importer.getToContext().getAtomicType(*UnderlyingTypeOrErr); 1079 } 1080 1081 ExpectedType ASTNodeImporter::VisitBuiltinType(const BuiltinType *T) { 1082 switch (T->getKind()) { 1083 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \ 1084 case BuiltinType::Id: \ 1085 return Importer.getToContext().SingletonId; 1086 #include "clang/Basic/OpenCLImageTypes.def" 1087 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \ 1088 case BuiltinType::Id: \ 1089 return Importer.getToContext().Id##Ty; 1090 #include "clang/Basic/OpenCLExtensionTypes.def" 1091 #define SVE_TYPE(Name, Id, SingletonId) \ 1092 case BuiltinType::Id: \ 1093 return Importer.getToContext().SingletonId; 1094 #include "clang/Basic/AArch64SVEACLETypes.def" 1095 #define PPC_VECTOR_TYPE(Name, Id, Size) \ 1096 case BuiltinType::Id: \ 1097 return Importer.getToContext().Id##Ty; 1098 #include "clang/Basic/PPCTypes.def" 1099 #define RVV_TYPE(Name, Id, SingletonId) \ 1100 case BuiltinType::Id: \ 1101 return Importer.getToContext().SingletonId; 1102 #include "clang/Basic/RISCVVTypes.def" 1103 #define WASM_TYPE(Name, Id, SingletonId) \ 1104 case BuiltinType::Id: \ 1105 return Importer.getToContext().SingletonId; 1106 #include "clang/Basic/WebAssemblyReferenceTypes.def" 1107 #define SHARED_SINGLETON_TYPE(Expansion) 1108 #define BUILTIN_TYPE(Id, SingletonId) \ 1109 case BuiltinType::Id: return Importer.getToContext().SingletonId; 1110 #include "clang/AST/BuiltinTypes.def" 1111 1112 // FIXME: for Char16, Char32, and NullPtr, make sure that the "to" 1113 // context supports C++. 1114 1115 // FIXME: for ObjCId, ObjCClass, and ObjCSel, make sure that the "to" 1116 // context supports ObjC. 1117 1118 case BuiltinType::Char_U: 1119 // The context we're importing from has an unsigned 'char'. If we're 1120 // importing into a context with a signed 'char', translate to 1121 // 'unsigned char' instead. 1122 if (Importer.getToContext().getLangOpts().CharIsSigned) 1123 return Importer.getToContext().UnsignedCharTy; 1124 1125 return Importer.getToContext().CharTy; 1126 1127 case BuiltinType::Char_S: 1128 // The context we're importing from has an unsigned 'char'. If we're 1129 // importing into a context with a signed 'char', translate to 1130 // 'unsigned char' instead. 1131 if (!Importer.getToContext().getLangOpts().CharIsSigned) 1132 return Importer.getToContext().SignedCharTy; 1133 1134 return Importer.getToContext().CharTy; 1135 1136 case BuiltinType::WChar_S: 1137 case BuiltinType::WChar_U: 1138 // FIXME: If not in C++, shall we translate to the C equivalent of 1139 // wchar_t? 1140 return Importer.getToContext().WCharTy; 1141 } 1142 1143 llvm_unreachable("Invalid BuiltinType Kind!"); 1144 } 1145 1146 ExpectedType ASTNodeImporter::VisitDecayedType(const DecayedType *T) { 1147 ExpectedType ToOriginalTypeOrErr = import(T->getOriginalType()); 1148 if (!ToOriginalTypeOrErr) 1149 return ToOriginalTypeOrErr.takeError(); 1150 1151 return Importer.getToContext().getDecayedType(*ToOriginalTypeOrErr); 1152 } 1153 1154 ExpectedType ASTNodeImporter::VisitComplexType(const ComplexType *T) { 1155 ExpectedType ToElementTypeOrErr = import(T->getElementType()); 1156 if (!ToElementTypeOrErr) 1157 return ToElementTypeOrErr.takeError(); 1158 1159 return Importer.getToContext().getComplexType(*ToElementTypeOrErr); 1160 } 1161 1162 ExpectedType ASTNodeImporter::VisitPointerType(const PointerType *T) { 1163 ExpectedType ToPointeeTypeOrErr = import(T->getPointeeType()); 1164 if (!ToPointeeTypeOrErr) 1165 return ToPointeeTypeOrErr.takeError(); 1166 1167 return Importer.getToContext().getPointerType(*ToPointeeTypeOrErr); 1168 } 1169 1170 ExpectedType ASTNodeImporter::VisitBlockPointerType(const BlockPointerType *T) { 1171 // FIXME: Check for blocks support in "to" context. 1172 ExpectedType ToPointeeTypeOrErr = import(T->getPointeeType()); 1173 if (!ToPointeeTypeOrErr) 1174 return ToPointeeTypeOrErr.takeError(); 1175 1176 return Importer.getToContext().getBlockPointerType(*ToPointeeTypeOrErr); 1177 } 1178 1179 ExpectedType 1180 ASTNodeImporter::VisitLValueReferenceType(const LValueReferenceType *T) { 1181 // FIXME: Check for C++ support in "to" context. 1182 ExpectedType ToPointeeTypeOrErr = import(T->getPointeeTypeAsWritten()); 1183 if (!ToPointeeTypeOrErr) 1184 return ToPointeeTypeOrErr.takeError(); 1185 1186 return Importer.getToContext().getLValueReferenceType(*ToPointeeTypeOrErr); 1187 } 1188 1189 ExpectedType 1190 ASTNodeImporter::VisitRValueReferenceType(const RValueReferenceType *T) { 1191 // FIXME: Check for C++0x support in "to" context. 1192 ExpectedType ToPointeeTypeOrErr = import(T->getPointeeTypeAsWritten()); 1193 if (!ToPointeeTypeOrErr) 1194 return ToPointeeTypeOrErr.takeError(); 1195 1196 return Importer.getToContext().getRValueReferenceType(*ToPointeeTypeOrErr); 1197 } 1198 1199 ExpectedType 1200 ASTNodeImporter::VisitMemberPointerType(const MemberPointerType *T) { 1201 // FIXME: Check for C++ support in "to" context. 1202 ExpectedType ToPointeeTypeOrErr = import(T->getPointeeType()); 1203 if (!ToPointeeTypeOrErr) 1204 return ToPointeeTypeOrErr.takeError(); 1205 1206 ExpectedTypePtr ClassTypeOrErr = import(T->getClass()); 1207 if (!ClassTypeOrErr) 1208 return ClassTypeOrErr.takeError(); 1209 1210 return Importer.getToContext().getMemberPointerType(*ToPointeeTypeOrErr, 1211 *ClassTypeOrErr); 1212 } 1213 1214 ExpectedType 1215 ASTNodeImporter::VisitConstantArrayType(const ConstantArrayType *T) { 1216 Error Err = Error::success(); 1217 auto ToElementType = importChecked(Err, T->getElementType()); 1218 auto ToSizeExpr = importChecked(Err, T->getSizeExpr()); 1219 if (Err) 1220 return std::move(Err); 1221 1222 return Importer.getToContext().getConstantArrayType( 1223 ToElementType, T->getSize(), ToSizeExpr, T->getSizeModifier(), 1224 T->getIndexTypeCVRQualifiers()); 1225 } 1226 1227 ExpectedType 1228 ASTNodeImporter::VisitIncompleteArrayType(const IncompleteArrayType *T) { 1229 ExpectedType ToElementTypeOrErr = import(T->getElementType()); 1230 if (!ToElementTypeOrErr) 1231 return ToElementTypeOrErr.takeError(); 1232 1233 return Importer.getToContext().getIncompleteArrayType(*ToElementTypeOrErr, 1234 T->getSizeModifier(), 1235 T->getIndexTypeCVRQualifiers()); 1236 } 1237 1238 ExpectedType 1239 ASTNodeImporter::VisitVariableArrayType(const VariableArrayType *T) { 1240 Error Err = Error::success(); 1241 QualType ToElementType = importChecked(Err, T->getElementType()); 1242 Expr *ToSizeExpr = importChecked(Err, T->getSizeExpr()); 1243 SourceRange ToBracketsRange = importChecked(Err, T->getBracketsRange()); 1244 if (Err) 1245 return std::move(Err); 1246 return Importer.getToContext().getVariableArrayType( 1247 ToElementType, ToSizeExpr, T->getSizeModifier(), 1248 T->getIndexTypeCVRQualifiers(), ToBracketsRange); 1249 } 1250 1251 ExpectedType ASTNodeImporter::VisitDependentSizedArrayType( 1252 const DependentSizedArrayType *T) { 1253 Error Err = Error::success(); 1254 QualType ToElementType = importChecked(Err, T->getElementType()); 1255 Expr *ToSizeExpr = importChecked(Err, T->getSizeExpr()); 1256 SourceRange ToBracketsRange = importChecked(Err, T->getBracketsRange()); 1257 if (Err) 1258 return std::move(Err); 1259 // SizeExpr may be null if size is not specified directly. 1260 // For example, 'int a[]'. 1261 1262 return Importer.getToContext().getDependentSizedArrayType( 1263 ToElementType, ToSizeExpr, T->getSizeModifier(), 1264 T->getIndexTypeCVRQualifiers(), ToBracketsRange); 1265 } 1266 1267 ExpectedType ASTNodeImporter::VisitVectorType(const VectorType *T) { 1268 ExpectedType ToElementTypeOrErr = import(T->getElementType()); 1269 if (!ToElementTypeOrErr) 1270 return ToElementTypeOrErr.takeError(); 1271 1272 return Importer.getToContext().getVectorType(*ToElementTypeOrErr, 1273 T->getNumElements(), 1274 T->getVectorKind()); 1275 } 1276 1277 ExpectedType ASTNodeImporter::VisitExtVectorType(const ExtVectorType *T) { 1278 ExpectedType ToElementTypeOrErr = import(T->getElementType()); 1279 if (!ToElementTypeOrErr) 1280 return ToElementTypeOrErr.takeError(); 1281 1282 return Importer.getToContext().getExtVectorType(*ToElementTypeOrErr, 1283 T->getNumElements()); 1284 } 1285 1286 ExpectedType 1287 ASTNodeImporter::VisitFunctionNoProtoType(const FunctionNoProtoType *T) { 1288 // FIXME: What happens if we're importing a function without a prototype 1289 // into C++? Should we make it variadic? 1290 ExpectedType ToReturnTypeOrErr = import(T->getReturnType()); 1291 if (!ToReturnTypeOrErr) 1292 return ToReturnTypeOrErr.takeError(); 1293 1294 return Importer.getToContext().getFunctionNoProtoType(*ToReturnTypeOrErr, 1295 T->getExtInfo()); 1296 } 1297 1298 ExpectedType 1299 ASTNodeImporter::VisitFunctionProtoType(const FunctionProtoType *T) { 1300 ExpectedType ToReturnTypeOrErr = import(T->getReturnType()); 1301 if (!ToReturnTypeOrErr) 1302 return ToReturnTypeOrErr.takeError(); 1303 1304 // Import argument types 1305 SmallVector<QualType, 4> ArgTypes; 1306 for (const auto &A : T->param_types()) { 1307 ExpectedType TyOrErr = import(A); 1308 if (!TyOrErr) 1309 return TyOrErr.takeError(); 1310 ArgTypes.push_back(*TyOrErr); 1311 } 1312 1313 // Import exception types 1314 SmallVector<QualType, 4> ExceptionTypes; 1315 for (const auto &E : T->exceptions()) { 1316 ExpectedType TyOrErr = import(E); 1317 if (!TyOrErr) 1318 return TyOrErr.takeError(); 1319 ExceptionTypes.push_back(*TyOrErr); 1320 } 1321 1322 FunctionProtoType::ExtProtoInfo FromEPI = T->getExtProtoInfo(); 1323 Error Err = Error::success(); 1324 FunctionProtoType::ExtProtoInfo ToEPI; 1325 ToEPI.ExtInfo = FromEPI.ExtInfo; 1326 ToEPI.Variadic = FromEPI.Variadic; 1327 ToEPI.HasTrailingReturn = FromEPI.HasTrailingReturn; 1328 ToEPI.TypeQuals = FromEPI.TypeQuals; 1329 ToEPI.RefQualifier = FromEPI.RefQualifier; 1330 ToEPI.ExceptionSpec.Type = FromEPI.ExceptionSpec.Type; 1331 ToEPI.ExceptionSpec.NoexceptExpr = 1332 importChecked(Err, FromEPI.ExceptionSpec.NoexceptExpr); 1333 ToEPI.ExceptionSpec.SourceDecl = 1334 importChecked(Err, FromEPI.ExceptionSpec.SourceDecl); 1335 ToEPI.ExceptionSpec.SourceTemplate = 1336 importChecked(Err, FromEPI.ExceptionSpec.SourceTemplate); 1337 ToEPI.ExceptionSpec.Exceptions = ExceptionTypes; 1338 1339 if (Err) 1340 return std::move(Err); 1341 1342 return Importer.getToContext().getFunctionType( 1343 *ToReturnTypeOrErr, ArgTypes, ToEPI); 1344 } 1345 1346 ExpectedType ASTNodeImporter::VisitUnresolvedUsingType( 1347 const UnresolvedUsingType *T) { 1348 Error Err = Error::success(); 1349 auto ToD = importChecked(Err, T->getDecl()); 1350 auto ToPrevD = importChecked(Err, T->getDecl()->getPreviousDecl()); 1351 if (Err) 1352 return std::move(Err); 1353 1354 return Importer.getToContext().getTypeDeclType( 1355 ToD, cast_or_null<TypeDecl>(ToPrevD)); 1356 } 1357 1358 ExpectedType ASTNodeImporter::VisitParenType(const ParenType *T) { 1359 ExpectedType ToInnerTypeOrErr = import(T->getInnerType()); 1360 if (!ToInnerTypeOrErr) 1361 return ToInnerTypeOrErr.takeError(); 1362 1363 return Importer.getToContext().getParenType(*ToInnerTypeOrErr); 1364 } 1365 1366 ExpectedType ASTNodeImporter::VisitTypedefType(const TypedefType *T) { 1367 Expected<TypedefNameDecl *> ToDeclOrErr = import(T->getDecl()); 1368 if (!ToDeclOrErr) 1369 return ToDeclOrErr.takeError(); 1370 1371 TypedefNameDecl *ToDecl = *ToDeclOrErr; 1372 if (ToDecl->getTypeForDecl()) 1373 return QualType(ToDecl->getTypeForDecl(), 0); 1374 1375 ExpectedType ToUnderlyingTypeOrErr = import(T->desugar()); 1376 if (!ToUnderlyingTypeOrErr) 1377 return ToUnderlyingTypeOrErr.takeError(); 1378 1379 return Importer.getToContext().getTypedefType(ToDecl, *ToUnderlyingTypeOrErr); 1380 } 1381 1382 ExpectedType ASTNodeImporter::VisitTypeOfExprType(const TypeOfExprType *T) { 1383 ExpectedExpr ToExprOrErr = import(T->getUnderlyingExpr()); 1384 if (!ToExprOrErr) 1385 return ToExprOrErr.takeError(); 1386 return Importer.getToContext().getTypeOfExprType(*ToExprOrErr, T->getKind()); 1387 } 1388 1389 ExpectedType ASTNodeImporter::VisitTypeOfType(const TypeOfType *T) { 1390 ExpectedType ToUnderlyingTypeOrErr = import(T->getUnmodifiedType()); 1391 if (!ToUnderlyingTypeOrErr) 1392 return ToUnderlyingTypeOrErr.takeError(); 1393 return Importer.getToContext().getTypeOfType(*ToUnderlyingTypeOrErr, 1394 T->getKind()); 1395 } 1396 1397 ExpectedType ASTNodeImporter::VisitUsingType(const UsingType *T) { 1398 Expected<UsingShadowDecl *> FoundOrErr = import(T->getFoundDecl()); 1399 if (!FoundOrErr) 1400 return FoundOrErr.takeError(); 1401 Expected<QualType> UnderlyingOrErr = import(T->getUnderlyingType()); 1402 if (!UnderlyingOrErr) 1403 return UnderlyingOrErr.takeError(); 1404 1405 return Importer.getToContext().getUsingType(*FoundOrErr, *UnderlyingOrErr); 1406 } 1407 1408 ExpectedType ASTNodeImporter::VisitDecltypeType(const DecltypeType *T) { 1409 // FIXME: Make sure that the "to" context supports C++0x! 1410 ExpectedExpr ToExprOrErr = import(T->getUnderlyingExpr()); 1411 if (!ToExprOrErr) 1412 return ToExprOrErr.takeError(); 1413 1414 ExpectedType ToUnderlyingTypeOrErr = import(T->getUnderlyingType()); 1415 if (!ToUnderlyingTypeOrErr) 1416 return ToUnderlyingTypeOrErr.takeError(); 1417 1418 return Importer.getToContext().getDecltypeType( 1419 *ToExprOrErr, *ToUnderlyingTypeOrErr); 1420 } 1421 1422 ExpectedType 1423 ASTNodeImporter::VisitUnaryTransformType(const UnaryTransformType *T) { 1424 ExpectedType ToBaseTypeOrErr = import(T->getBaseType()); 1425 if (!ToBaseTypeOrErr) 1426 return ToBaseTypeOrErr.takeError(); 1427 1428 ExpectedType ToUnderlyingTypeOrErr = import(T->getUnderlyingType()); 1429 if (!ToUnderlyingTypeOrErr) 1430 return ToUnderlyingTypeOrErr.takeError(); 1431 1432 return Importer.getToContext().getUnaryTransformType( 1433 *ToBaseTypeOrErr, *ToUnderlyingTypeOrErr, T->getUTTKind()); 1434 } 1435 1436 ExpectedType ASTNodeImporter::VisitAutoType(const AutoType *T) { 1437 // FIXME: Make sure that the "to" context supports C++11! 1438 ExpectedType ToDeducedTypeOrErr = import(T->getDeducedType()); 1439 if (!ToDeducedTypeOrErr) 1440 return ToDeducedTypeOrErr.takeError(); 1441 1442 ExpectedDecl ToTypeConstraintConcept = import(T->getTypeConstraintConcept()); 1443 if (!ToTypeConstraintConcept) 1444 return ToTypeConstraintConcept.takeError(); 1445 1446 SmallVector<TemplateArgument, 2> ToTemplateArgs; 1447 if (Error Err = ImportTemplateArguments(T->getTypeConstraintArguments(), 1448 ToTemplateArgs)) 1449 return std::move(Err); 1450 1451 return Importer.getToContext().getAutoType( 1452 *ToDeducedTypeOrErr, T->getKeyword(), /*IsDependent*/false, 1453 /*IsPack=*/false, cast_or_null<ConceptDecl>(*ToTypeConstraintConcept), 1454 ToTemplateArgs); 1455 } 1456 1457 ExpectedType ASTNodeImporter::VisitDeducedTemplateSpecializationType( 1458 const DeducedTemplateSpecializationType *T) { 1459 // FIXME: Make sure that the "to" context supports C++17! 1460 Expected<TemplateName> ToTemplateNameOrErr = import(T->getTemplateName()); 1461 if (!ToTemplateNameOrErr) 1462 return ToTemplateNameOrErr.takeError(); 1463 ExpectedType ToDeducedTypeOrErr = import(T->getDeducedType()); 1464 if (!ToDeducedTypeOrErr) 1465 return ToDeducedTypeOrErr.takeError(); 1466 1467 return Importer.getToContext().getDeducedTemplateSpecializationType( 1468 *ToTemplateNameOrErr, *ToDeducedTypeOrErr, T->isDependentType()); 1469 } 1470 1471 ExpectedType ASTNodeImporter::VisitInjectedClassNameType( 1472 const InjectedClassNameType *T) { 1473 Expected<CXXRecordDecl *> ToDeclOrErr = import(T->getDecl()); 1474 if (!ToDeclOrErr) 1475 return ToDeclOrErr.takeError(); 1476 1477 // The InjectedClassNameType is created in VisitRecordDecl when the 1478 // T->getDecl() is imported. Here we can return the existing type. 1479 const Type *Ty = (*ToDeclOrErr)->getTypeForDecl(); 1480 assert(Ty && isa<InjectedClassNameType>(Ty)); 1481 return QualType(Ty, 0); 1482 } 1483 1484 ExpectedType ASTNodeImporter::VisitRecordType(const RecordType *T) { 1485 Expected<RecordDecl *> ToDeclOrErr = import(T->getDecl()); 1486 if (!ToDeclOrErr) 1487 return ToDeclOrErr.takeError(); 1488 1489 return Importer.getToContext().getTagDeclType(*ToDeclOrErr); 1490 } 1491 1492 ExpectedType ASTNodeImporter::VisitEnumType(const EnumType *T) { 1493 Expected<EnumDecl *> ToDeclOrErr = import(T->getDecl()); 1494 if (!ToDeclOrErr) 1495 return ToDeclOrErr.takeError(); 1496 1497 return Importer.getToContext().getTagDeclType(*ToDeclOrErr); 1498 } 1499 1500 ExpectedType ASTNodeImporter::VisitAttributedType(const AttributedType *T) { 1501 ExpectedType ToModifiedTypeOrErr = import(T->getModifiedType()); 1502 if (!ToModifiedTypeOrErr) 1503 return ToModifiedTypeOrErr.takeError(); 1504 ExpectedType ToEquivalentTypeOrErr = import(T->getEquivalentType()); 1505 if (!ToEquivalentTypeOrErr) 1506 return ToEquivalentTypeOrErr.takeError(); 1507 1508 return Importer.getToContext().getAttributedType(T->getAttrKind(), 1509 *ToModifiedTypeOrErr, *ToEquivalentTypeOrErr); 1510 } 1511 1512 ExpectedType ASTNodeImporter::VisitTemplateTypeParmType( 1513 const TemplateTypeParmType *T) { 1514 Expected<TemplateTypeParmDecl *> ToDeclOrErr = import(T->getDecl()); 1515 if (!ToDeclOrErr) 1516 return ToDeclOrErr.takeError(); 1517 1518 return Importer.getToContext().getTemplateTypeParmType( 1519 T->getDepth(), T->getIndex(), T->isParameterPack(), *ToDeclOrErr); 1520 } 1521 1522 ExpectedType ASTNodeImporter::VisitSubstTemplateTypeParmType( 1523 const SubstTemplateTypeParmType *T) { 1524 Expected<Decl *> ReplacedOrErr = import(T->getAssociatedDecl()); 1525 if (!ReplacedOrErr) 1526 return ReplacedOrErr.takeError(); 1527 1528 ExpectedType ToReplacementTypeOrErr = import(T->getReplacementType()); 1529 if (!ToReplacementTypeOrErr) 1530 return ToReplacementTypeOrErr.takeError(); 1531 1532 return Importer.getToContext().getSubstTemplateTypeParmType( 1533 *ToReplacementTypeOrErr, *ReplacedOrErr, T->getIndex(), 1534 T->getPackIndex()); 1535 } 1536 1537 ExpectedType ASTNodeImporter::VisitSubstTemplateTypeParmPackType( 1538 const SubstTemplateTypeParmPackType *T) { 1539 Expected<Decl *> ReplacedOrErr = import(T->getAssociatedDecl()); 1540 if (!ReplacedOrErr) 1541 return ReplacedOrErr.takeError(); 1542 1543 Expected<TemplateArgument> ToArgumentPack = import(T->getArgumentPack()); 1544 if (!ToArgumentPack) 1545 return ToArgumentPack.takeError(); 1546 1547 return Importer.getToContext().getSubstTemplateTypeParmPackType( 1548 *ReplacedOrErr, T->getIndex(), T->getFinal(), *ToArgumentPack); 1549 } 1550 1551 ExpectedType ASTNodeImporter::VisitTemplateSpecializationType( 1552 const TemplateSpecializationType *T) { 1553 auto ToTemplateOrErr = import(T->getTemplateName()); 1554 if (!ToTemplateOrErr) 1555 return ToTemplateOrErr.takeError(); 1556 1557 SmallVector<TemplateArgument, 2> ToTemplateArgs; 1558 if (Error Err = 1559 ImportTemplateArguments(T->template_arguments(), ToTemplateArgs)) 1560 return std::move(Err); 1561 1562 QualType ToCanonType; 1563 if (!T->isCanonicalUnqualified()) { 1564 QualType FromCanonType 1565 = Importer.getFromContext().getCanonicalType(QualType(T, 0)); 1566 if (ExpectedType TyOrErr = import(FromCanonType)) 1567 ToCanonType = *TyOrErr; 1568 else 1569 return TyOrErr.takeError(); 1570 } 1571 return Importer.getToContext().getTemplateSpecializationType(*ToTemplateOrErr, 1572 ToTemplateArgs, 1573 ToCanonType); 1574 } 1575 1576 ExpectedType ASTNodeImporter::VisitElaboratedType(const ElaboratedType *T) { 1577 // Note: the qualifier in an ElaboratedType is optional. 1578 auto ToQualifierOrErr = import(T->getQualifier()); 1579 if (!ToQualifierOrErr) 1580 return ToQualifierOrErr.takeError(); 1581 1582 ExpectedType ToNamedTypeOrErr = import(T->getNamedType()); 1583 if (!ToNamedTypeOrErr) 1584 return ToNamedTypeOrErr.takeError(); 1585 1586 Expected<TagDecl *> ToOwnedTagDeclOrErr = import(T->getOwnedTagDecl()); 1587 if (!ToOwnedTagDeclOrErr) 1588 return ToOwnedTagDeclOrErr.takeError(); 1589 1590 return Importer.getToContext().getElaboratedType(T->getKeyword(), 1591 *ToQualifierOrErr, 1592 *ToNamedTypeOrErr, 1593 *ToOwnedTagDeclOrErr); 1594 } 1595 1596 ExpectedType 1597 ASTNodeImporter::VisitPackExpansionType(const PackExpansionType *T) { 1598 ExpectedType ToPatternOrErr = import(T->getPattern()); 1599 if (!ToPatternOrErr) 1600 return ToPatternOrErr.takeError(); 1601 1602 return Importer.getToContext().getPackExpansionType(*ToPatternOrErr, 1603 T->getNumExpansions(), 1604 /*ExpactPack=*/false); 1605 } 1606 1607 ExpectedType ASTNodeImporter::VisitDependentTemplateSpecializationType( 1608 const DependentTemplateSpecializationType *T) { 1609 auto ToQualifierOrErr = import(T->getQualifier()); 1610 if (!ToQualifierOrErr) 1611 return ToQualifierOrErr.takeError(); 1612 1613 IdentifierInfo *ToName = Importer.Import(T->getIdentifier()); 1614 1615 SmallVector<TemplateArgument, 2> ToPack; 1616 ToPack.reserve(T->template_arguments().size()); 1617 if (Error Err = ImportTemplateArguments(T->template_arguments(), ToPack)) 1618 return std::move(Err); 1619 1620 return Importer.getToContext().getDependentTemplateSpecializationType( 1621 T->getKeyword(), *ToQualifierOrErr, ToName, ToPack); 1622 } 1623 1624 ExpectedType 1625 ASTNodeImporter::VisitDependentNameType(const DependentNameType *T) { 1626 auto ToQualifierOrErr = import(T->getQualifier()); 1627 if (!ToQualifierOrErr) 1628 return ToQualifierOrErr.takeError(); 1629 1630 IdentifierInfo *Name = Importer.Import(T->getIdentifier()); 1631 1632 QualType Canon; 1633 if (T != T->getCanonicalTypeInternal().getTypePtr()) { 1634 if (ExpectedType TyOrErr = import(T->getCanonicalTypeInternal())) 1635 Canon = (*TyOrErr).getCanonicalType(); 1636 else 1637 return TyOrErr.takeError(); 1638 } 1639 1640 return Importer.getToContext().getDependentNameType(T->getKeyword(), 1641 *ToQualifierOrErr, 1642 Name, Canon); 1643 } 1644 1645 ExpectedType 1646 ASTNodeImporter::VisitObjCInterfaceType(const ObjCInterfaceType *T) { 1647 Expected<ObjCInterfaceDecl *> ToDeclOrErr = import(T->getDecl()); 1648 if (!ToDeclOrErr) 1649 return ToDeclOrErr.takeError(); 1650 1651 return Importer.getToContext().getObjCInterfaceType(*ToDeclOrErr); 1652 } 1653 1654 ExpectedType ASTNodeImporter::VisitObjCObjectType(const ObjCObjectType *T) { 1655 ExpectedType ToBaseTypeOrErr = import(T->getBaseType()); 1656 if (!ToBaseTypeOrErr) 1657 return ToBaseTypeOrErr.takeError(); 1658 1659 SmallVector<QualType, 4> TypeArgs; 1660 for (auto TypeArg : T->getTypeArgsAsWritten()) { 1661 if (ExpectedType TyOrErr = import(TypeArg)) 1662 TypeArgs.push_back(*TyOrErr); 1663 else 1664 return TyOrErr.takeError(); 1665 } 1666 1667 SmallVector<ObjCProtocolDecl *, 4> Protocols; 1668 for (auto *P : T->quals()) { 1669 if (Expected<ObjCProtocolDecl *> ProtocolOrErr = import(P)) 1670 Protocols.push_back(*ProtocolOrErr); 1671 else 1672 return ProtocolOrErr.takeError(); 1673 1674 } 1675 1676 return Importer.getToContext().getObjCObjectType(*ToBaseTypeOrErr, TypeArgs, 1677 Protocols, 1678 T->isKindOfTypeAsWritten()); 1679 } 1680 1681 ExpectedType 1682 ASTNodeImporter::VisitObjCObjectPointerType(const ObjCObjectPointerType *T) { 1683 ExpectedType ToPointeeTypeOrErr = import(T->getPointeeType()); 1684 if (!ToPointeeTypeOrErr) 1685 return ToPointeeTypeOrErr.takeError(); 1686 1687 return Importer.getToContext().getObjCObjectPointerType(*ToPointeeTypeOrErr); 1688 } 1689 1690 //---------------------------------------------------------------------------- 1691 // Import Declarations 1692 //---------------------------------------------------------------------------- 1693 Error ASTNodeImporter::ImportDeclParts( 1694 NamedDecl *D, DeclContext *&DC, DeclContext *&LexicalDC, 1695 DeclarationName &Name, NamedDecl *&ToD, SourceLocation &Loc) { 1696 // Check if RecordDecl is in FunctionDecl parameters to avoid infinite loop. 1697 // example: int struct_in_proto(struct data_t{int a;int b;} *d); 1698 // FIXME: We could support these constructs by importing a different type of 1699 // this parameter and by importing the original type of the parameter only 1700 // after the FunctionDecl is created. See 1701 // VisitFunctionDecl::UsedDifferentProtoType. 1702 DeclContext *OrigDC = D->getDeclContext(); 1703 FunctionDecl *FunDecl; 1704 if (isa<RecordDecl>(D) && (FunDecl = dyn_cast<FunctionDecl>(OrigDC)) && 1705 FunDecl->hasBody()) { 1706 auto getLeafPointeeType = [](const Type *T) { 1707 while (T->isPointerType() || T->isArrayType()) { 1708 T = T->getPointeeOrArrayElementType(); 1709 } 1710 return T; 1711 }; 1712 for (const ParmVarDecl *P : FunDecl->parameters()) { 1713 const Type *LeafT = 1714 getLeafPointeeType(P->getType().getCanonicalType().getTypePtr()); 1715 auto *RT = dyn_cast<RecordType>(LeafT); 1716 if (RT && RT->getDecl() == D) { 1717 Importer.FromDiag(D->getLocation(), diag::err_unsupported_ast_node) 1718 << D->getDeclKindName(); 1719 return make_error<ASTImportError>(ASTImportError::UnsupportedConstruct); 1720 } 1721 } 1722 } 1723 1724 // Import the context of this declaration. 1725 if (Error Err = ImportDeclContext(D, DC, LexicalDC)) 1726 return Err; 1727 1728 // Import the name of this declaration. 1729 if (Error Err = importInto(Name, D->getDeclName())) 1730 return Err; 1731 1732 // Import the location of this declaration. 1733 if (Error Err = importInto(Loc, D->getLocation())) 1734 return Err; 1735 1736 ToD = cast_or_null<NamedDecl>(Importer.GetAlreadyImportedOrNull(D)); 1737 if (ToD) 1738 if (Error Err = ASTNodeImporter(*this).ImportDefinitionIfNeeded(D, ToD)) 1739 return Err; 1740 1741 return Error::success(); 1742 } 1743 1744 Error ASTNodeImporter::ImportDeclParts(NamedDecl *D, DeclarationName &Name, 1745 NamedDecl *&ToD, SourceLocation &Loc) { 1746 1747 // Import the name of this declaration. 1748 if (Error Err = importInto(Name, D->getDeclName())) 1749 return Err; 1750 1751 // Import the location of this declaration. 1752 if (Error Err = importInto(Loc, D->getLocation())) 1753 return Err; 1754 1755 ToD = cast_or_null<NamedDecl>(Importer.GetAlreadyImportedOrNull(D)); 1756 if (ToD) 1757 if (Error Err = ASTNodeImporter(*this).ImportDefinitionIfNeeded(D, ToD)) 1758 return Err; 1759 1760 return Error::success(); 1761 } 1762 1763 Error ASTNodeImporter::ImportDefinitionIfNeeded(Decl *FromD, Decl *ToD) { 1764 if (!FromD) 1765 return Error::success(); 1766 1767 if (!ToD) 1768 if (Error Err = importInto(ToD, FromD)) 1769 return Err; 1770 1771 if (RecordDecl *FromRecord = dyn_cast<RecordDecl>(FromD)) { 1772 if (RecordDecl *ToRecord = cast<RecordDecl>(ToD)) { 1773 if (FromRecord->getDefinition() && FromRecord->isCompleteDefinition() && 1774 !ToRecord->getDefinition()) { 1775 if (Error Err = ImportDefinition(FromRecord, ToRecord)) 1776 return Err; 1777 } 1778 } 1779 return Error::success(); 1780 } 1781 1782 if (EnumDecl *FromEnum = dyn_cast<EnumDecl>(FromD)) { 1783 if (EnumDecl *ToEnum = cast<EnumDecl>(ToD)) { 1784 if (FromEnum->getDefinition() && !ToEnum->getDefinition()) { 1785 if (Error Err = ImportDefinition(FromEnum, ToEnum)) 1786 return Err; 1787 } 1788 } 1789 return Error::success(); 1790 } 1791 1792 return Error::success(); 1793 } 1794 1795 Error 1796 ASTNodeImporter::ImportDeclarationNameLoc( 1797 const DeclarationNameInfo &From, DeclarationNameInfo& To) { 1798 // NOTE: To.Name and To.Loc are already imported. 1799 // We only have to import To.LocInfo. 1800 switch (To.getName().getNameKind()) { 1801 case DeclarationName::Identifier: 1802 case DeclarationName::ObjCZeroArgSelector: 1803 case DeclarationName::ObjCOneArgSelector: 1804 case DeclarationName::ObjCMultiArgSelector: 1805 case DeclarationName::CXXUsingDirective: 1806 case DeclarationName::CXXDeductionGuideName: 1807 return Error::success(); 1808 1809 case DeclarationName::CXXOperatorName: { 1810 if (auto ToRangeOrErr = import(From.getCXXOperatorNameRange())) 1811 To.setCXXOperatorNameRange(*ToRangeOrErr); 1812 else 1813 return ToRangeOrErr.takeError(); 1814 return Error::success(); 1815 } 1816 case DeclarationName::CXXLiteralOperatorName: { 1817 if (ExpectedSLoc LocOrErr = import(From.getCXXLiteralOperatorNameLoc())) 1818 To.setCXXLiteralOperatorNameLoc(*LocOrErr); 1819 else 1820 return LocOrErr.takeError(); 1821 return Error::success(); 1822 } 1823 case DeclarationName::CXXConstructorName: 1824 case DeclarationName::CXXDestructorName: 1825 case DeclarationName::CXXConversionFunctionName: { 1826 if (auto ToTInfoOrErr = import(From.getNamedTypeInfo())) 1827 To.setNamedTypeInfo(*ToTInfoOrErr); 1828 else 1829 return ToTInfoOrErr.takeError(); 1830 return Error::success(); 1831 } 1832 } 1833 llvm_unreachable("Unknown name kind."); 1834 } 1835 1836 Error 1837 ASTNodeImporter::ImportDeclContext(DeclContext *FromDC, bool ForceImport) { 1838 if (Importer.isMinimalImport() && !ForceImport) { 1839 auto ToDCOrErr = Importer.ImportContext(FromDC); 1840 return ToDCOrErr.takeError(); 1841 } 1842 1843 // We use strict error handling in case of records and enums, but not 1844 // with e.g. namespaces. 1845 // 1846 // FIXME Clients of the ASTImporter should be able to choose an 1847 // appropriate error handling strategy for their needs. For instance, 1848 // they may not want to mark an entire namespace as erroneous merely 1849 // because there is an ODR error with two typedefs. As another example, 1850 // the client may allow EnumConstantDecls with same names but with 1851 // different values in two distinct translation units. 1852 ChildErrorHandlingStrategy HandleChildErrors(FromDC); 1853 1854 auto MightNeedReordering = [](const Decl *D) { 1855 return isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D) || isa<FriendDecl>(D); 1856 }; 1857 1858 // Import everything that might need reordering first. 1859 Error ChildErrors = Error::success(); 1860 for (auto *From : FromDC->decls()) { 1861 if (!MightNeedReordering(From)) 1862 continue; 1863 1864 ExpectedDecl ImportedOrErr = import(From); 1865 1866 // If we are in the process of ImportDefinition(...) for a RecordDecl we 1867 // want to make sure that we are also completing each FieldDecl. There 1868 // are currently cases where this does not happen and this is correctness 1869 // fix since operations such as code generation will expect this to be so. 1870 if (!ImportedOrErr) { 1871 HandleChildErrors.handleChildImportResult(ChildErrors, 1872 ImportedOrErr.takeError()); 1873 continue; 1874 } 1875 FieldDecl *FieldFrom = dyn_cast_or_null<FieldDecl>(From); 1876 Decl *ImportedDecl = *ImportedOrErr; 1877 FieldDecl *FieldTo = dyn_cast_or_null<FieldDecl>(ImportedDecl); 1878 if (FieldFrom && FieldTo) { 1879 Error Err = ImportFieldDeclDefinition(FieldFrom, FieldTo); 1880 HandleChildErrors.handleChildImportResult(ChildErrors, std::move(Err)); 1881 } 1882 } 1883 1884 // We reorder declarations in RecordDecls because they may have another order 1885 // in the "to" context than they have in the "from" context. This may happen 1886 // e.g when we import a class like this: 1887 // struct declToImport { 1888 // int a = c + b; 1889 // int b = 1; 1890 // int c = 2; 1891 // }; 1892 // During the import of `a` we import first the dependencies in sequence, 1893 // thus the order would be `c`, `b`, `a`. We will get the normal order by 1894 // first removing the already imported members and then adding them in the 1895 // order as they appear in the "from" context. 1896 // 1897 // Keeping field order is vital because it determines structure layout. 1898 // 1899 // Here and below, we cannot call field_begin() method and its callers on 1900 // ToDC if it has an external storage. Calling field_begin() will 1901 // automatically load all the fields by calling 1902 // LoadFieldsFromExternalStorage(). LoadFieldsFromExternalStorage() would 1903 // call ASTImporter::Import(). This is because the ExternalASTSource 1904 // interface in LLDB is implemented by the means of the ASTImporter. However, 1905 // calling an import at this point would result in an uncontrolled import, we 1906 // must avoid that. 1907 1908 auto ToDCOrErr = Importer.ImportContext(FromDC); 1909 if (!ToDCOrErr) { 1910 consumeError(std::move(ChildErrors)); 1911 return ToDCOrErr.takeError(); 1912 } 1913 1914 DeclContext *ToDC = *ToDCOrErr; 1915 // Remove all declarations, which may be in wrong order in the 1916 // lexical DeclContext and then add them in the proper order. 1917 for (auto *D : FromDC->decls()) { 1918 if (!MightNeedReordering(D)) 1919 continue; 1920 1921 assert(D && "DC contains a null decl"); 1922 if (Decl *ToD = Importer.GetAlreadyImportedOrNull(D)) { 1923 // Remove only the decls which we successfully imported. 1924 assert(ToDC == ToD->getLexicalDeclContext() && ToDC->containsDecl(ToD)); 1925 // Remove the decl from its wrong place in the linked list. 1926 ToDC->removeDecl(ToD); 1927 // Add the decl to the end of the linked list. 1928 // This time it will be at the proper place because the enclosing for 1929 // loop iterates in the original (good) order of the decls. 1930 ToDC->addDeclInternal(ToD); 1931 } 1932 } 1933 1934 // Import everything else. 1935 for (auto *From : FromDC->decls()) { 1936 if (MightNeedReordering(From)) 1937 continue; 1938 1939 ExpectedDecl ImportedOrErr = import(From); 1940 if (!ImportedOrErr) 1941 HandleChildErrors.handleChildImportResult(ChildErrors, 1942 ImportedOrErr.takeError()); 1943 } 1944 1945 return ChildErrors; 1946 } 1947 1948 Error ASTNodeImporter::ImportFieldDeclDefinition(const FieldDecl *From, 1949 const FieldDecl *To) { 1950 RecordDecl *FromRecordDecl = nullptr; 1951 RecordDecl *ToRecordDecl = nullptr; 1952 // If we have a field that is an ArrayType we need to check if the array 1953 // element is a RecordDecl and if so we need to import the definition. 1954 QualType FromType = From->getType(); 1955 QualType ToType = To->getType(); 1956 if (FromType->isArrayType()) { 1957 // getBaseElementTypeUnsafe(...) handles multi-dimensonal arrays for us. 1958 FromRecordDecl = FromType->getBaseElementTypeUnsafe()->getAsRecordDecl(); 1959 ToRecordDecl = ToType->getBaseElementTypeUnsafe()->getAsRecordDecl(); 1960 } 1961 1962 if (!FromRecordDecl || !ToRecordDecl) { 1963 const RecordType *RecordFrom = FromType->getAs<RecordType>(); 1964 const RecordType *RecordTo = ToType->getAs<RecordType>(); 1965 1966 if (RecordFrom && RecordTo) { 1967 FromRecordDecl = RecordFrom->getDecl(); 1968 ToRecordDecl = RecordTo->getDecl(); 1969 } 1970 } 1971 1972 if (FromRecordDecl && ToRecordDecl) { 1973 if (FromRecordDecl->isCompleteDefinition() && 1974 !ToRecordDecl->isCompleteDefinition()) 1975 return ImportDefinition(FromRecordDecl, ToRecordDecl); 1976 } 1977 1978 return Error::success(); 1979 } 1980 1981 Error ASTNodeImporter::ImportDeclContext( 1982 Decl *FromD, DeclContext *&ToDC, DeclContext *&ToLexicalDC) { 1983 auto ToDCOrErr = Importer.ImportContext(FromD->getDeclContext()); 1984 if (!ToDCOrErr) 1985 return ToDCOrErr.takeError(); 1986 ToDC = *ToDCOrErr; 1987 1988 if (FromD->getDeclContext() != FromD->getLexicalDeclContext()) { 1989 auto ToLexicalDCOrErr = Importer.ImportContext( 1990 FromD->getLexicalDeclContext()); 1991 if (!ToLexicalDCOrErr) 1992 return ToLexicalDCOrErr.takeError(); 1993 ToLexicalDC = *ToLexicalDCOrErr; 1994 } else 1995 ToLexicalDC = ToDC; 1996 1997 return Error::success(); 1998 } 1999 2000 Error ASTNodeImporter::ImportImplicitMethods( 2001 const CXXRecordDecl *From, CXXRecordDecl *To) { 2002 assert(From->isCompleteDefinition() && To->getDefinition() == To && 2003 "Import implicit methods to or from non-definition"); 2004 2005 for (CXXMethodDecl *FromM : From->methods()) 2006 if (FromM->isImplicit()) { 2007 Expected<CXXMethodDecl *> ToMOrErr = import(FromM); 2008 if (!ToMOrErr) 2009 return ToMOrErr.takeError(); 2010 } 2011 2012 return Error::success(); 2013 } 2014 2015 static Error setTypedefNameForAnonDecl(TagDecl *From, TagDecl *To, 2016 ASTImporter &Importer) { 2017 if (TypedefNameDecl *FromTypedef = From->getTypedefNameForAnonDecl()) { 2018 if (ExpectedDecl ToTypedefOrErr = Importer.Import(FromTypedef)) 2019 To->setTypedefNameForAnonDecl(cast<TypedefNameDecl>(*ToTypedefOrErr)); 2020 else 2021 return ToTypedefOrErr.takeError(); 2022 } 2023 return Error::success(); 2024 } 2025 2026 Error ASTNodeImporter::ImportDefinition( 2027 RecordDecl *From, RecordDecl *To, ImportDefinitionKind Kind) { 2028 auto DefinitionCompleter = [To]() { 2029 // There are cases in LLDB when we first import a class without its 2030 // members. The class will have DefinitionData, but no members. Then, 2031 // importDefinition is called from LLDB, which tries to get the members, so 2032 // when we get here, the class already has the DefinitionData set, so we 2033 // must unset the CompleteDefinition here to be able to complete again the 2034 // definition. 2035 To->setCompleteDefinition(false); 2036 To->completeDefinition(); 2037 }; 2038 2039 if (To->getDefinition() || To->isBeingDefined()) { 2040 if (Kind == IDK_Everything || 2041 // In case of lambdas, the class already has a definition ptr set, but 2042 // the contained decls are not imported yet. Also, isBeingDefined was 2043 // set in CXXRecordDecl::CreateLambda. We must import the contained 2044 // decls here and finish the definition. 2045 (To->isLambda() && shouldForceImportDeclContext(Kind))) { 2046 if (To->isLambda()) { 2047 auto *FromCXXRD = cast<CXXRecordDecl>(From); 2048 SmallVector<LambdaCapture, 8> ToCaptures; 2049 ToCaptures.reserve(FromCXXRD->capture_size()); 2050 for (const auto &FromCapture : FromCXXRD->captures()) { 2051 if (auto ToCaptureOrErr = import(FromCapture)) 2052 ToCaptures.push_back(*ToCaptureOrErr); 2053 else 2054 return ToCaptureOrErr.takeError(); 2055 } 2056 cast<CXXRecordDecl>(To)->setCaptures(Importer.getToContext(), 2057 ToCaptures); 2058 } 2059 2060 Error Result = ImportDeclContext(From, /*ForceImport=*/true); 2061 // Finish the definition of the lambda, set isBeingDefined to false. 2062 if (To->isLambda()) 2063 DefinitionCompleter(); 2064 return Result; 2065 } 2066 2067 return Error::success(); 2068 } 2069 2070 To->startDefinition(); 2071 // Set the definition to complete even if it is really not complete during 2072 // import. Some AST constructs (expressions) require the record layout 2073 // to be calculated (see 'clang::computeDependence') at the time they are 2074 // constructed. Import of such AST node is possible during import of the 2075 // same record, there is no way to have a completely defined record (all 2076 // fields imported) at that time without multiple AST import passes. 2077 if (!Importer.isMinimalImport()) 2078 To->setCompleteDefinition(true); 2079 // Complete the definition even if error is returned. 2080 // The RecordDecl may be already part of the AST so it is better to 2081 // have it in complete state even if something is wrong with it. 2082 auto DefinitionCompleterScopeExit = 2083 llvm::make_scope_exit(DefinitionCompleter); 2084 2085 if (Error Err = setTypedefNameForAnonDecl(From, To, Importer)) 2086 return Err; 2087 2088 // Add base classes. 2089 auto *ToCXX = dyn_cast<CXXRecordDecl>(To); 2090 auto *FromCXX = dyn_cast<CXXRecordDecl>(From); 2091 if (ToCXX && FromCXX && ToCXX->dataPtr() && FromCXX->dataPtr()) { 2092 2093 struct CXXRecordDecl::DefinitionData &ToData = ToCXX->data(); 2094 struct CXXRecordDecl::DefinitionData &FromData = FromCXX->data(); 2095 2096 #define FIELD(Name, Width, Merge) \ 2097 ToData.Name = FromData.Name; 2098 #include "clang/AST/CXXRecordDeclDefinitionBits.def" 2099 2100 // Copy over the data stored in RecordDeclBits 2101 ToCXX->setArgPassingRestrictions(FromCXX->getArgPassingRestrictions()); 2102 2103 SmallVector<CXXBaseSpecifier *, 4> Bases; 2104 for (const auto &Base1 : FromCXX->bases()) { 2105 ExpectedType TyOrErr = import(Base1.getType()); 2106 if (!TyOrErr) 2107 return TyOrErr.takeError(); 2108 2109 SourceLocation EllipsisLoc; 2110 if (Base1.isPackExpansion()) { 2111 if (ExpectedSLoc LocOrErr = import(Base1.getEllipsisLoc())) 2112 EllipsisLoc = *LocOrErr; 2113 else 2114 return LocOrErr.takeError(); 2115 } 2116 2117 // Ensure that we have a definition for the base. 2118 if (Error Err = 2119 ImportDefinitionIfNeeded(Base1.getType()->getAsCXXRecordDecl())) 2120 return Err; 2121 2122 auto RangeOrErr = import(Base1.getSourceRange()); 2123 if (!RangeOrErr) 2124 return RangeOrErr.takeError(); 2125 2126 auto TSIOrErr = import(Base1.getTypeSourceInfo()); 2127 if (!TSIOrErr) 2128 return TSIOrErr.takeError(); 2129 2130 Bases.push_back( 2131 new (Importer.getToContext()) CXXBaseSpecifier( 2132 *RangeOrErr, 2133 Base1.isVirtual(), 2134 Base1.isBaseOfClass(), 2135 Base1.getAccessSpecifierAsWritten(), 2136 *TSIOrErr, 2137 EllipsisLoc)); 2138 } 2139 if (!Bases.empty()) 2140 ToCXX->setBases(Bases.data(), Bases.size()); 2141 } 2142 2143 if (shouldForceImportDeclContext(Kind)) { 2144 if (Error Err = ImportDeclContext(From, /*ForceImport=*/true)) 2145 return Err; 2146 } 2147 2148 return Error::success(); 2149 } 2150 2151 Error ASTNodeImporter::ImportInitializer(VarDecl *From, VarDecl *To) { 2152 if (To->getAnyInitializer()) 2153 return Error::success(); 2154 2155 Expr *FromInit = From->getInit(); 2156 if (!FromInit) 2157 return Error::success(); 2158 2159 ExpectedExpr ToInitOrErr = import(FromInit); 2160 if (!ToInitOrErr) 2161 return ToInitOrErr.takeError(); 2162 2163 To->setInit(*ToInitOrErr); 2164 if (EvaluatedStmt *FromEval = From->getEvaluatedStmt()) { 2165 EvaluatedStmt *ToEval = To->ensureEvaluatedStmt(); 2166 ToEval->HasConstantInitialization = FromEval->HasConstantInitialization; 2167 ToEval->HasConstantDestruction = FromEval->HasConstantDestruction; 2168 // FIXME: Also import the initializer value. 2169 } 2170 2171 // FIXME: Other bits to merge? 2172 return Error::success(); 2173 } 2174 2175 Error ASTNodeImporter::ImportDefinition( 2176 EnumDecl *From, EnumDecl *To, ImportDefinitionKind Kind) { 2177 if (To->getDefinition() || To->isBeingDefined()) { 2178 if (Kind == IDK_Everything) 2179 return ImportDeclContext(From, /*ForceImport=*/true); 2180 return Error::success(); 2181 } 2182 2183 To->startDefinition(); 2184 2185 if (Error Err = setTypedefNameForAnonDecl(From, To, Importer)) 2186 return Err; 2187 2188 ExpectedType ToTypeOrErr = 2189 import(Importer.getFromContext().getTypeDeclType(From)); 2190 if (!ToTypeOrErr) 2191 return ToTypeOrErr.takeError(); 2192 2193 ExpectedType ToPromotionTypeOrErr = import(From->getPromotionType()); 2194 if (!ToPromotionTypeOrErr) 2195 return ToPromotionTypeOrErr.takeError(); 2196 2197 if (shouldForceImportDeclContext(Kind)) 2198 if (Error Err = ImportDeclContext(From, /*ForceImport=*/true)) 2199 return Err; 2200 2201 // FIXME: we might need to merge the number of positive or negative bits 2202 // if the enumerator lists don't match. 2203 To->completeDefinition(*ToTypeOrErr, *ToPromotionTypeOrErr, 2204 From->getNumPositiveBits(), 2205 From->getNumNegativeBits()); 2206 return Error::success(); 2207 } 2208 2209 Error ASTNodeImporter::ImportTemplateArguments( 2210 ArrayRef<TemplateArgument> FromArgs, 2211 SmallVectorImpl<TemplateArgument> &ToArgs) { 2212 for (const auto &Arg : FromArgs) { 2213 if (auto ToOrErr = import(Arg)) 2214 ToArgs.push_back(*ToOrErr); 2215 else 2216 return ToOrErr.takeError(); 2217 } 2218 2219 return Error::success(); 2220 } 2221 2222 // FIXME: Do not forget to remove this and use only 'import'. 2223 Expected<TemplateArgument> 2224 ASTNodeImporter::ImportTemplateArgument(const TemplateArgument &From) { 2225 return import(From); 2226 } 2227 2228 template <typename InContainerTy> 2229 Error ASTNodeImporter::ImportTemplateArgumentListInfo( 2230 const InContainerTy &Container, TemplateArgumentListInfo &ToTAInfo) { 2231 for (const auto &FromLoc : Container) { 2232 if (auto ToLocOrErr = import(FromLoc)) 2233 ToTAInfo.addArgument(*ToLocOrErr); 2234 else 2235 return ToLocOrErr.takeError(); 2236 } 2237 return Error::success(); 2238 } 2239 2240 static StructuralEquivalenceKind 2241 getStructuralEquivalenceKind(const ASTImporter &Importer) { 2242 return Importer.isMinimalImport() ? StructuralEquivalenceKind::Minimal 2243 : StructuralEquivalenceKind::Default; 2244 } 2245 2246 bool ASTNodeImporter::IsStructuralMatch(Decl *From, Decl *To, bool Complain) { 2247 // Eliminate a potential failure point where we attempt to re-import 2248 // something we're trying to import while completing ToRecord. 2249 Decl *ToOrigin = Importer.GetOriginalDecl(To); 2250 if (ToOrigin) { 2251 To = ToOrigin; 2252 } 2253 2254 StructuralEquivalenceContext Ctx( 2255 Importer.getFromContext(), Importer.getToContext(), 2256 Importer.getNonEquivalentDecls(), getStructuralEquivalenceKind(Importer), 2257 false, Complain); 2258 return Ctx.IsEquivalent(From, To); 2259 } 2260 2261 ExpectedDecl ASTNodeImporter::VisitDecl(Decl *D) { 2262 Importer.FromDiag(D->getLocation(), diag::err_unsupported_ast_node) 2263 << D->getDeclKindName(); 2264 return make_error<ASTImportError>(ASTImportError::UnsupportedConstruct); 2265 } 2266 2267 ExpectedDecl ASTNodeImporter::VisitImportDecl(ImportDecl *D) { 2268 Importer.FromDiag(D->getLocation(), diag::err_unsupported_ast_node) 2269 << D->getDeclKindName(); 2270 return make_error<ASTImportError>(ASTImportError::UnsupportedConstruct); 2271 } 2272 2273 ExpectedDecl ASTNodeImporter::VisitEmptyDecl(EmptyDecl *D) { 2274 // Import the context of this declaration. 2275 DeclContext *DC, *LexicalDC; 2276 if (Error Err = ImportDeclContext(D, DC, LexicalDC)) 2277 return std::move(Err); 2278 2279 // Import the location of this declaration. 2280 ExpectedSLoc LocOrErr = import(D->getLocation()); 2281 if (!LocOrErr) 2282 return LocOrErr.takeError(); 2283 2284 EmptyDecl *ToD; 2285 if (GetImportedOrCreateDecl(ToD, D, Importer.getToContext(), DC, *LocOrErr)) 2286 return ToD; 2287 2288 ToD->setLexicalDeclContext(LexicalDC); 2289 LexicalDC->addDeclInternal(ToD); 2290 return ToD; 2291 } 2292 2293 ExpectedDecl ASTNodeImporter::VisitTranslationUnitDecl(TranslationUnitDecl *D) { 2294 TranslationUnitDecl *ToD = 2295 Importer.getToContext().getTranslationUnitDecl(); 2296 2297 Importer.MapImported(D, ToD); 2298 2299 return ToD; 2300 } 2301 2302 ExpectedDecl ASTNodeImporter::VisitBindingDecl(BindingDecl *D) { 2303 DeclContext *DC, *LexicalDC; 2304 DeclarationName Name; 2305 SourceLocation Loc; 2306 NamedDecl *ToND; 2307 if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToND, Loc)) 2308 return std::move(Err); 2309 if (ToND) 2310 return ToND; 2311 2312 BindingDecl *ToD; 2313 if (GetImportedOrCreateDecl(ToD, D, Importer.getToContext(), DC, Loc, 2314 Name.getAsIdentifierInfo())) 2315 return ToD; 2316 2317 Error Err = Error::success(); 2318 QualType ToType = importChecked(Err, D->getType()); 2319 Expr *ToBinding = importChecked(Err, D->getBinding()); 2320 ValueDecl *ToDecomposedDecl = importChecked(Err, D->getDecomposedDecl()); 2321 if (Err) 2322 return std::move(Err); 2323 2324 ToD->setBinding(ToType, ToBinding); 2325 ToD->setDecomposedDecl(ToDecomposedDecl); 2326 addDeclToContexts(D, ToD); 2327 2328 return ToD; 2329 } 2330 2331 ExpectedDecl ASTNodeImporter::VisitAccessSpecDecl(AccessSpecDecl *D) { 2332 ExpectedSLoc LocOrErr = import(D->getLocation()); 2333 if (!LocOrErr) 2334 return LocOrErr.takeError(); 2335 auto ColonLocOrErr = import(D->getColonLoc()); 2336 if (!ColonLocOrErr) 2337 return ColonLocOrErr.takeError(); 2338 2339 // Import the context of this declaration. 2340 auto DCOrErr = Importer.ImportContext(D->getDeclContext()); 2341 if (!DCOrErr) 2342 return DCOrErr.takeError(); 2343 DeclContext *DC = *DCOrErr; 2344 2345 AccessSpecDecl *ToD; 2346 if (GetImportedOrCreateDecl(ToD, D, Importer.getToContext(), D->getAccess(), 2347 DC, *LocOrErr, *ColonLocOrErr)) 2348 return ToD; 2349 2350 // Lexical DeclContext and Semantic DeclContext 2351 // is always the same for the accessSpec. 2352 ToD->setLexicalDeclContext(DC); 2353 DC->addDeclInternal(ToD); 2354 2355 return ToD; 2356 } 2357 2358 ExpectedDecl ASTNodeImporter::VisitStaticAssertDecl(StaticAssertDecl *D) { 2359 auto DCOrErr = Importer.ImportContext(D->getDeclContext()); 2360 if (!DCOrErr) 2361 return DCOrErr.takeError(); 2362 DeclContext *DC = *DCOrErr; 2363 DeclContext *LexicalDC = DC; 2364 2365 Error Err = Error::success(); 2366 auto ToLocation = importChecked(Err, D->getLocation()); 2367 auto ToRParenLoc = importChecked(Err, D->getRParenLoc()); 2368 auto ToAssertExpr = importChecked(Err, D->getAssertExpr()); 2369 auto ToMessage = importChecked(Err, D->getMessage()); 2370 if (Err) 2371 return std::move(Err); 2372 2373 StaticAssertDecl *ToD; 2374 if (GetImportedOrCreateDecl( 2375 ToD, D, Importer.getToContext(), DC, ToLocation, ToAssertExpr, ToMessage, 2376 ToRParenLoc, D->isFailed())) 2377 return ToD; 2378 2379 ToD->setLexicalDeclContext(LexicalDC); 2380 LexicalDC->addDeclInternal(ToD); 2381 return ToD; 2382 } 2383 2384 ExpectedDecl ASTNodeImporter::VisitNamespaceDecl(NamespaceDecl *D) { 2385 // Import the major distinguishing characteristics of this namespace. 2386 DeclContext *DC, *LexicalDC; 2387 DeclarationName Name; 2388 SourceLocation Loc; 2389 NamedDecl *ToD; 2390 if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc)) 2391 return std::move(Err); 2392 if (ToD) 2393 return ToD; 2394 2395 NamespaceDecl *MergeWithNamespace = nullptr; 2396 if (!Name) { 2397 // This is an anonymous namespace. Adopt an existing anonymous 2398 // namespace if we can. 2399 // FIXME: Not testable. 2400 if (auto *TU = dyn_cast<TranslationUnitDecl>(DC)) 2401 MergeWithNamespace = TU->getAnonymousNamespace(); 2402 else 2403 MergeWithNamespace = cast<NamespaceDecl>(DC)->getAnonymousNamespace(); 2404 } else { 2405 SmallVector<NamedDecl *, 4> ConflictingDecls; 2406 auto FoundDecls = Importer.findDeclsInToCtx(DC, Name); 2407 for (auto *FoundDecl : FoundDecls) { 2408 if (!FoundDecl->isInIdentifierNamespace(Decl::IDNS_Namespace)) 2409 continue; 2410 2411 if (auto *FoundNS = dyn_cast<NamespaceDecl>(FoundDecl)) { 2412 MergeWithNamespace = FoundNS; 2413 ConflictingDecls.clear(); 2414 break; 2415 } 2416 2417 ConflictingDecls.push_back(FoundDecl); 2418 } 2419 2420 if (!ConflictingDecls.empty()) { 2421 ExpectedName NameOrErr = Importer.HandleNameConflict( 2422 Name, DC, Decl::IDNS_Namespace, ConflictingDecls.data(), 2423 ConflictingDecls.size()); 2424 if (NameOrErr) 2425 Name = NameOrErr.get(); 2426 else 2427 return NameOrErr.takeError(); 2428 } 2429 } 2430 2431 ExpectedSLoc BeginLocOrErr = import(D->getBeginLoc()); 2432 if (!BeginLocOrErr) 2433 return BeginLocOrErr.takeError(); 2434 ExpectedSLoc RBraceLocOrErr = import(D->getRBraceLoc()); 2435 if (!RBraceLocOrErr) 2436 return RBraceLocOrErr.takeError(); 2437 2438 // Create the "to" namespace, if needed. 2439 NamespaceDecl *ToNamespace = MergeWithNamespace; 2440 if (!ToNamespace) { 2441 if (GetImportedOrCreateDecl(ToNamespace, D, Importer.getToContext(), DC, 2442 D->isInline(), *BeginLocOrErr, Loc, 2443 Name.getAsIdentifierInfo(), 2444 /*PrevDecl=*/nullptr, D->isNested())) 2445 return ToNamespace; 2446 ToNamespace->setRBraceLoc(*RBraceLocOrErr); 2447 ToNamespace->setLexicalDeclContext(LexicalDC); 2448 LexicalDC->addDeclInternal(ToNamespace); 2449 2450 // If this is an anonymous namespace, register it as the anonymous 2451 // namespace within its context. 2452 if (!Name) { 2453 if (auto *TU = dyn_cast<TranslationUnitDecl>(DC)) 2454 TU->setAnonymousNamespace(ToNamespace); 2455 else 2456 cast<NamespaceDecl>(DC)->setAnonymousNamespace(ToNamespace); 2457 } 2458 } 2459 Importer.MapImported(D, ToNamespace); 2460 2461 if (Error Err = ImportDeclContext(D)) 2462 return std::move(Err); 2463 2464 return ToNamespace; 2465 } 2466 2467 ExpectedDecl ASTNodeImporter::VisitNamespaceAliasDecl(NamespaceAliasDecl *D) { 2468 // Import the major distinguishing characteristics of this namespace. 2469 DeclContext *DC, *LexicalDC; 2470 DeclarationName Name; 2471 SourceLocation Loc; 2472 NamedDecl *LookupD; 2473 if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, LookupD, Loc)) 2474 return std::move(Err); 2475 if (LookupD) 2476 return LookupD; 2477 2478 // NOTE: No conflict resolution is done for namespace aliases now. 2479 2480 Error Err = Error::success(); 2481 auto ToNamespaceLoc = importChecked(Err, D->getNamespaceLoc()); 2482 auto ToAliasLoc = importChecked(Err, D->getAliasLoc()); 2483 auto ToQualifierLoc = importChecked(Err, D->getQualifierLoc()); 2484 auto ToTargetNameLoc = importChecked(Err, D->getTargetNameLoc()); 2485 auto ToNamespace = importChecked(Err, D->getNamespace()); 2486 if (Err) 2487 return std::move(Err); 2488 2489 IdentifierInfo *ToIdentifier = Importer.Import(D->getIdentifier()); 2490 2491 NamespaceAliasDecl *ToD; 2492 if (GetImportedOrCreateDecl( 2493 ToD, D, Importer.getToContext(), DC, ToNamespaceLoc, ToAliasLoc, 2494 ToIdentifier, ToQualifierLoc, ToTargetNameLoc, ToNamespace)) 2495 return ToD; 2496 2497 ToD->setLexicalDeclContext(LexicalDC); 2498 LexicalDC->addDeclInternal(ToD); 2499 2500 return ToD; 2501 } 2502 2503 ExpectedDecl 2504 ASTNodeImporter::VisitTypedefNameDecl(TypedefNameDecl *D, bool IsAlias) { 2505 // Import the major distinguishing characteristics of this typedef. 2506 DeclarationName Name; 2507 SourceLocation Loc; 2508 NamedDecl *ToD; 2509 // Do not import the DeclContext, we will import it once the TypedefNameDecl 2510 // is created. 2511 if (Error Err = ImportDeclParts(D, Name, ToD, Loc)) 2512 return std::move(Err); 2513 if (ToD) 2514 return ToD; 2515 2516 DeclContext *DC = cast_or_null<DeclContext>( 2517 Importer.GetAlreadyImportedOrNull(cast<Decl>(D->getDeclContext()))); 2518 DeclContext *LexicalDC = 2519 cast_or_null<DeclContext>(Importer.GetAlreadyImportedOrNull( 2520 cast<Decl>(D->getLexicalDeclContext()))); 2521 2522 // If this typedef is not in block scope, determine whether we've 2523 // seen a typedef with the same name (that we can merge with) or any 2524 // other entity by that name (which name lookup could conflict with). 2525 // Note: Repeated typedefs are not valid in C99: 2526 // 'typedef int T; typedef int T;' is invalid 2527 // We do not care about this now. 2528 if (DC && !DC->isFunctionOrMethod()) { 2529 SmallVector<NamedDecl *, 4> ConflictingDecls; 2530 unsigned IDNS = Decl::IDNS_Ordinary; 2531 auto FoundDecls = Importer.findDeclsInToCtx(DC, Name); 2532 for (auto *FoundDecl : FoundDecls) { 2533 if (!FoundDecl->isInIdentifierNamespace(IDNS)) 2534 continue; 2535 if (auto *FoundTypedef = dyn_cast<TypedefNameDecl>(FoundDecl)) { 2536 if (!hasSameVisibilityContextAndLinkage(FoundTypedef, D)) 2537 continue; 2538 2539 QualType FromUT = D->getUnderlyingType(); 2540 QualType FoundUT = FoundTypedef->getUnderlyingType(); 2541 if (Importer.IsStructurallyEquivalent(FromUT, FoundUT)) { 2542 // If the underlying declarations are unnamed records these can be 2543 // imported as different types. We should create a distinct typedef 2544 // node in this case. 2545 // If we found an existing underlying type with a record in a 2546 // different context (than the imported), this is already reason for 2547 // having distinct typedef nodes for these. 2548 // Again this can create situation like 2549 // 'typedef int T; typedef int T;' but this is hard to avoid without 2550 // a rename strategy at import. 2551 if (!FromUT.isNull() && !FoundUT.isNull()) { 2552 RecordDecl *FromR = FromUT->getAsRecordDecl(); 2553 RecordDecl *FoundR = FoundUT->getAsRecordDecl(); 2554 if (FromR && FoundR && 2555 !hasSameVisibilityContextAndLinkage(FoundR, FromR)) 2556 continue; 2557 } 2558 // If the "From" context has a complete underlying type but we 2559 // already have a complete underlying type then return with that. 2560 if (!FromUT->isIncompleteType() && !FoundUT->isIncompleteType()) 2561 return Importer.MapImported(D, FoundTypedef); 2562 // FIXME Handle redecl chain. When you do that make consistent changes 2563 // in ASTImporterLookupTable too. 2564 } else { 2565 ConflictingDecls.push_back(FoundDecl); 2566 } 2567 } 2568 } 2569 2570 if (!ConflictingDecls.empty()) { 2571 ExpectedName NameOrErr = Importer.HandleNameConflict( 2572 Name, DC, IDNS, ConflictingDecls.data(), ConflictingDecls.size()); 2573 if (NameOrErr) 2574 Name = NameOrErr.get(); 2575 else 2576 return NameOrErr.takeError(); 2577 } 2578 } 2579 2580 Error Err = Error::success(); 2581 auto ToUnderlyingType = importChecked(Err, D->getUnderlyingType()); 2582 auto ToTypeSourceInfo = importChecked(Err, D->getTypeSourceInfo()); 2583 auto ToBeginLoc = importChecked(Err, D->getBeginLoc()); 2584 if (Err) 2585 return std::move(Err); 2586 2587 // Create the new typedef node. 2588 // FIXME: ToUnderlyingType is not used. 2589 (void)ToUnderlyingType; 2590 TypedefNameDecl *ToTypedef; 2591 if (IsAlias) { 2592 if (GetImportedOrCreateDecl<TypeAliasDecl>( 2593 ToTypedef, D, Importer.getToContext(), DC, ToBeginLoc, Loc, 2594 Name.getAsIdentifierInfo(), ToTypeSourceInfo)) 2595 return ToTypedef; 2596 } else if (GetImportedOrCreateDecl<TypedefDecl>( 2597 ToTypedef, D, Importer.getToContext(), DC, ToBeginLoc, Loc, 2598 Name.getAsIdentifierInfo(), ToTypeSourceInfo)) 2599 return ToTypedef; 2600 2601 // Import the DeclContext and set it to the Typedef. 2602 if ((Err = ImportDeclContext(D, DC, LexicalDC))) 2603 return std::move(Err); 2604 ToTypedef->setDeclContext(DC); 2605 ToTypedef->setLexicalDeclContext(LexicalDC); 2606 // Add to the lookupTable because we could not do that in MapImported. 2607 Importer.AddToLookupTable(ToTypedef); 2608 2609 ToTypedef->setAccess(D->getAccess()); 2610 2611 // Templated declarations should not appear in DeclContext. 2612 TypeAliasDecl *FromAlias = IsAlias ? cast<TypeAliasDecl>(D) : nullptr; 2613 if (!FromAlias || !FromAlias->getDescribedAliasTemplate()) 2614 LexicalDC->addDeclInternal(ToTypedef); 2615 2616 return ToTypedef; 2617 } 2618 2619 ExpectedDecl ASTNodeImporter::VisitTypedefDecl(TypedefDecl *D) { 2620 return VisitTypedefNameDecl(D, /*IsAlias=*/false); 2621 } 2622 2623 ExpectedDecl ASTNodeImporter::VisitTypeAliasDecl(TypeAliasDecl *D) { 2624 return VisitTypedefNameDecl(D, /*IsAlias=*/true); 2625 } 2626 2627 ExpectedDecl 2628 ASTNodeImporter::VisitTypeAliasTemplateDecl(TypeAliasTemplateDecl *D) { 2629 // Import the major distinguishing characteristics of this typedef. 2630 DeclContext *DC, *LexicalDC; 2631 DeclarationName Name; 2632 SourceLocation Loc; 2633 NamedDecl *FoundD; 2634 if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, FoundD, Loc)) 2635 return std::move(Err); 2636 if (FoundD) 2637 return FoundD; 2638 2639 // If this typedef is not in block scope, determine whether we've 2640 // seen a typedef with the same name (that we can merge with) or any 2641 // other entity by that name (which name lookup could conflict with). 2642 if (!DC->isFunctionOrMethod()) { 2643 SmallVector<NamedDecl *, 4> ConflictingDecls; 2644 unsigned IDNS = Decl::IDNS_Ordinary; 2645 auto FoundDecls = Importer.findDeclsInToCtx(DC, Name); 2646 for (auto *FoundDecl : FoundDecls) { 2647 if (!FoundDecl->isInIdentifierNamespace(IDNS)) 2648 continue; 2649 if (auto *FoundAlias = dyn_cast<TypeAliasTemplateDecl>(FoundDecl)) 2650 return Importer.MapImported(D, FoundAlias); 2651 ConflictingDecls.push_back(FoundDecl); 2652 } 2653 2654 if (!ConflictingDecls.empty()) { 2655 ExpectedName NameOrErr = Importer.HandleNameConflict( 2656 Name, DC, IDNS, ConflictingDecls.data(), ConflictingDecls.size()); 2657 if (NameOrErr) 2658 Name = NameOrErr.get(); 2659 else 2660 return NameOrErr.takeError(); 2661 } 2662 } 2663 2664 Error Err = Error::success(); 2665 auto ToTemplateParameters = importChecked(Err, D->getTemplateParameters()); 2666 auto ToTemplatedDecl = importChecked(Err, D->getTemplatedDecl()); 2667 if (Err) 2668 return std::move(Err); 2669 2670 TypeAliasTemplateDecl *ToAlias; 2671 if (GetImportedOrCreateDecl(ToAlias, D, Importer.getToContext(), DC, Loc, 2672 Name, ToTemplateParameters, ToTemplatedDecl)) 2673 return ToAlias; 2674 2675 ToTemplatedDecl->setDescribedAliasTemplate(ToAlias); 2676 2677 ToAlias->setAccess(D->getAccess()); 2678 ToAlias->setLexicalDeclContext(LexicalDC); 2679 LexicalDC->addDeclInternal(ToAlias); 2680 if (DC != Importer.getToContext().getTranslationUnitDecl()) 2681 updateLookupTableForTemplateParameters(*ToTemplateParameters); 2682 return ToAlias; 2683 } 2684 2685 ExpectedDecl ASTNodeImporter::VisitLabelDecl(LabelDecl *D) { 2686 // Import the major distinguishing characteristics of this label. 2687 DeclContext *DC, *LexicalDC; 2688 DeclarationName Name; 2689 SourceLocation Loc; 2690 NamedDecl *ToD; 2691 if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc)) 2692 return std::move(Err); 2693 if (ToD) 2694 return ToD; 2695 2696 assert(LexicalDC->isFunctionOrMethod()); 2697 2698 LabelDecl *ToLabel; 2699 if (D->isGnuLocal()) { 2700 ExpectedSLoc BeginLocOrErr = import(D->getBeginLoc()); 2701 if (!BeginLocOrErr) 2702 return BeginLocOrErr.takeError(); 2703 if (GetImportedOrCreateDecl(ToLabel, D, Importer.getToContext(), DC, Loc, 2704 Name.getAsIdentifierInfo(), *BeginLocOrErr)) 2705 return ToLabel; 2706 2707 } else { 2708 if (GetImportedOrCreateDecl(ToLabel, D, Importer.getToContext(), DC, Loc, 2709 Name.getAsIdentifierInfo())) 2710 return ToLabel; 2711 2712 } 2713 2714 Expected<LabelStmt *> ToStmtOrErr = import(D->getStmt()); 2715 if (!ToStmtOrErr) 2716 return ToStmtOrErr.takeError(); 2717 2718 ToLabel->setStmt(*ToStmtOrErr); 2719 ToLabel->setLexicalDeclContext(LexicalDC); 2720 LexicalDC->addDeclInternal(ToLabel); 2721 return ToLabel; 2722 } 2723 2724 ExpectedDecl ASTNodeImporter::VisitEnumDecl(EnumDecl *D) { 2725 // Import the major distinguishing characteristics of this enum. 2726 DeclContext *DC, *LexicalDC; 2727 DeclarationName Name; 2728 SourceLocation Loc; 2729 NamedDecl *ToD; 2730 if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc)) 2731 return std::move(Err); 2732 if (ToD) 2733 return ToD; 2734 2735 // Figure out what enum name we're looking for. 2736 unsigned IDNS = Decl::IDNS_Tag; 2737 DeclarationName SearchName = Name; 2738 if (!SearchName && D->getTypedefNameForAnonDecl()) { 2739 if (Error Err = importInto( 2740 SearchName, D->getTypedefNameForAnonDecl()->getDeclName())) 2741 return std::move(Err); 2742 IDNS = Decl::IDNS_Ordinary; 2743 } else if (Importer.getToContext().getLangOpts().CPlusPlus) 2744 IDNS |= Decl::IDNS_Ordinary; 2745 2746 // We may already have an enum of the same name; try to find and match it. 2747 EnumDecl *PrevDecl = nullptr; 2748 if (!DC->isFunctionOrMethod() && SearchName) { 2749 SmallVector<NamedDecl *, 4> ConflictingDecls; 2750 auto FoundDecls = 2751 Importer.findDeclsInToCtx(DC, SearchName); 2752 for (auto *FoundDecl : FoundDecls) { 2753 if (!FoundDecl->isInIdentifierNamespace(IDNS)) 2754 continue; 2755 2756 if (auto *Typedef = dyn_cast<TypedefNameDecl>(FoundDecl)) { 2757 if (const auto *Tag = Typedef->getUnderlyingType()->getAs<TagType>()) 2758 FoundDecl = Tag->getDecl(); 2759 } 2760 2761 if (auto *FoundEnum = dyn_cast<EnumDecl>(FoundDecl)) { 2762 if (!hasSameVisibilityContextAndLinkage(FoundEnum, D)) 2763 continue; 2764 if (IsStructuralMatch(D, FoundEnum)) { 2765 EnumDecl *FoundDef = FoundEnum->getDefinition(); 2766 if (D->isThisDeclarationADefinition() && FoundDef) 2767 return Importer.MapImported(D, FoundDef); 2768 PrevDecl = FoundEnum->getMostRecentDecl(); 2769 break; 2770 } 2771 ConflictingDecls.push_back(FoundDecl); 2772 } 2773 } 2774 2775 if (!ConflictingDecls.empty()) { 2776 ExpectedName NameOrErr = Importer.HandleNameConflict( 2777 SearchName, DC, IDNS, ConflictingDecls.data(), 2778 ConflictingDecls.size()); 2779 if (NameOrErr) 2780 Name = NameOrErr.get(); 2781 else 2782 return NameOrErr.takeError(); 2783 } 2784 } 2785 2786 Error Err = Error::success(); 2787 auto ToBeginLoc = importChecked(Err, D->getBeginLoc()); 2788 auto ToQualifierLoc = importChecked(Err, D->getQualifierLoc()); 2789 auto ToIntegerType = importChecked(Err, D->getIntegerType()); 2790 auto ToBraceRange = importChecked(Err, D->getBraceRange()); 2791 if (Err) 2792 return std::move(Err); 2793 2794 // Create the enum declaration. 2795 EnumDecl *D2; 2796 if (GetImportedOrCreateDecl( 2797 D2, D, Importer.getToContext(), DC, ToBeginLoc, 2798 Loc, Name.getAsIdentifierInfo(), PrevDecl, D->isScoped(), 2799 D->isScopedUsingClassTag(), D->isFixed())) 2800 return D2; 2801 2802 D2->setQualifierInfo(ToQualifierLoc); 2803 D2->setIntegerType(ToIntegerType); 2804 D2->setBraceRange(ToBraceRange); 2805 D2->setAccess(D->getAccess()); 2806 D2->setLexicalDeclContext(LexicalDC); 2807 addDeclToContexts(D, D2); 2808 2809 if (MemberSpecializationInfo *MemberInfo = D->getMemberSpecializationInfo()) { 2810 TemplateSpecializationKind SK = MemberInfo->getTemplateSpecializationKind(); 2811 EnumDecl *FromInst = D->getInstantiatedFromMemberEnum(); 2812 if (Expected<EnumDecl *> ToInstOrErr = import(FromInst)) 2813 D2->setInstantiationOfMemberEnum(*ToInstOrErr, SK); 2814 else 2815 return ToInstOrErr.takeError(); 2816 if (ExpectedSLoc POIOrErr = import(MemberInfo->getPointOfInstantiation())) 2817 D2->getMemberSpecializationInfo()->setPointOfInstantiation(*POIOrErr); 2818 else 2819 return POIOrErr.takeError(); 2820 } 2821 2822 // Import the definition 2823 if (D->isCompleteDefinition()) 2824 if (Error Err = ImportDefinition(D, D2)) 2825 return std::move(Err); 2826 2827 return D2; 2828 } 2829 2830 ExpectedDecl ASTNodeImporter::VisitRecordDecl(RecordDecl *D) { 2831 bool IsFriendTemplate = false; 2832 if (auto *DCXX = dyn_cast<CXXRecordDecl>(D)) { 2833 IsFriendTemplate = 2834 DCXX->getDescribedClassTemplate() && 2835 DCXX->getDescribedClassTemplate()->getFriendObjectKind() != 2836 Decl::FOK_None; 2837 } 2838 2839 // Import the major distinguishing characteristics of this record. 2840 DeclContext *DC = nullptr, *LexicalDC = nullptr; 2841 DeclarationName Name; 2842 SourceLocation Loc; 2843 NamedDecl *ToD = nullptr; 2844 if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc)) 2845 return std::move(Err); 2846 if (ToD) 2847 return ToD; 2848 2849 // Figure out what structure name we're looking for. 2850 unsigned IDNS = Decl::IDNS_Tag; 2851 DeclarationName SearchName = Name; 2852 if (!SearchName && D->getTypedefNameForAnonDecl()) { 2853 if (Error Err = importInto( 2854 SearchName, D->getTypedefNameForAnonDecl()->getDeclName())) 2855 return std::move(Err); 2856 IDNS = Decl::IDNS_Ordinary; 2857 } else if (Importer.getToContext().getLangOpts().CPlusPlus) 2858 IDNS |= Decl::IDNS_Ordinary | Decl::IDNS_TagFriend; 2859 2860 // We may already have a record of the same name; try to find and match it. 2861 RecordDecl *PrevDecl = nullptr; 2862 if (!DC->isFunctionOrMethod() && !D->isLambda()) { 2863 SmallVector<NamedDecl *, 4> ConflictingDecls; 2864 auto FoundDecls = 2865 Importer.findDeclsInToCtx(DC, SearchName); 2866 if (!FoundDecls.empty()) { 2867 // We're going to have to compare D against potentially conflicting Decls, 2868 // so complete it. 2869 if (D->hasExternalLexicalStorage() && !D->isCompleteDefinition()) 2870 D->getASTContext().getExternalSource()->CompleteType(D); 2871 } 2872 2873 for (auto *FoundDecl : FoundDecls) { 2874 if (!FoundDecl->isInIdentifierNamespace(IDNS)) 2875 continue; 2876 2877 Decl *Found = FoundDecl; 2878 if (auto *Typedef = dyn_cast<TypedefNameDecl>(Found)) { 2879 if (const auto *Tag = Typedef->getUnderlyingType()->getAs<TagType>()) 2880 Found = Tag->getDecl(); 2881 } 2882 2883 if (auto *FoundRecord = dyn_cast<RecordDecl>(Found)) { 2884 // Do not emit false positive diagnostic in case of unnamed 2885 // struct/union and in case of anonymous structs. Would be false 2886 // because there may be several anonymous/unnamed structs in a class. 2887 // E.g. these are both valid: 2888 // struct A { // unnamed structs 2889 // struct { struct A *next; } entry0; 2890 // struct { struct A *next; } entry1; 2891 // }; 2892 // struct X { struct { int a; }; struct { int b; }; }; // anon structs 2893 if (!SearchName) 2894 if (!IsStructuralMatch(D, FoundRecord, false)) 2895 continue; 2896 2897 if (!hasSameVisibilityContextAndLinkage(FoundRecord, D)) 2898 continue; 2899 2900 if (IsStructuralMatch(D, FoundRecord)) { 2901 RecordDecl *FoundDef = FoundRecord->getDefinition(); 2902 if (D->isThisDeclarationADefinition() && FoundDef) { 2903 // FIXME: Structural equivalence check should check for same 2904 // user-defined methods. 2905 Importer.MapImported(D, FoundDef); 2906 if (const auto *DCXX = dyn_cast<CXXRecordDecl>(D)) { 2907 auto *FoundCXX = dyn_cast<CXXRecordDecl>(FoundDef); 2908 assert(FoundCXX && "Record type mismatch"); 2909 2910 if (!Importer.isMinimalImport()) 2911 // FoundDef may not have every implicit method that D has 2912 // because implicit methods are created only if they are used. 2913 if (Error Err = ImportImplicitMethods(DCXX, FoundCXX)) 2914 return std::move(Err); 2915 } 2916 } 2917 PrevDecl = FoundRecord->getMostRecentDecl(); 2918 break; 2919 } 2920 ConflictingDecls.push_back(FoundDecl); 2921 } // kind is RecordDecl 2922 } // for 2923 2924 if (!ConflictingDecls.empty() && SearchName) { 2925 ExpectedName NameOrErr = Importer.HandleNameConflict( 2926 SearchName, DC, IDNS, ConflictingDecls.data(), 2927 ConflictingDecls.size()); 2928 if (NameOrErr) 2929 Name = NameOrErr.get(); 2930 else 2931 return NameOrErr.takeError(); 2932 } 2933 } 2934 2935 ExpectedSLoc BeginLocOrErr = import(D->getBeginLoc()); 2936 if (!BeginLocOrErr) 2937 return BeginLocOrErr.takeError(); 2938 2939 // Create the record declaration. 2940 RecordDecl *D2 = nullptr; 2941 CXXRecordDecl *D2CXX = nullptr; 2942 if (auto *DCXX = dyn_cast<CXXRecordDecl>(D)) { 2943 if (DCXX->isLambda()) { 2944 auto TInfoOrErr = import(DCXX->getLambdaTypeInfo()); 2945 if (!TInfoOrErr) 2946 return TInfoOrErr.takeError(); 2947 if (GetImportedOrCreateSpecialDecl( 2948 D2CXX, CXXRecordDecl::CreateLambda, D, Importer.getToContext(), 2949 DC, *TInfoOrErr, Loc, DCXX->getLambdaDependencyKind(), 2950 DCXX->isGenericLambda(), DCXX->getLambdaCaptureDefault())) 2951 return D2CXX; 2952 CXXRecordDecl::LambdaNumbering Numbering = DCXX->getLambdaNumbering(); 2953 ExpectedDecl CDeclOrErr = import(Numbering.ContextDecl); 2954 if (!CDeclOrErr) 2955 return CDeclOrErr.takeError(); 2956 Numbering.ContextDecl = *CDeclOrErr; 2957 D2CXX->setLambdaNumbering(Numbering); 2958 } else if (DCXX->isInjectedClassName()) { 2959 // We have to be careful to do a similar dance to the one in 2960 // Sema::ActOnStartCXXMemberDeclarations 2961 const bool DelayTypeCreation = true; 2962 if (GetImportedOrCreateDecl( 2963 D2CXX, D, Importer.getToContext(), D->getTagKind(), DC, 2964 *BeginLocOrErr, Loc, Name.getAsIdentifierInfo(), 2965 cast_or_null<CXXRecordDecl>(PrevDecl), DelayTypeCreation)) 2966 return D2CXX; 2967 Importer.getToContext().getTypeDeclType( 2968 D2CXX, dyn_cast<CXXRecordDecl>(DC)); 2969 } else { 2970 if (GetImportedOrCreateDecl(D2CXX, D, Importer.getToContext(), 2971 D->getTagKind(), DC, *BeginLocOrErr, Loc, 2972 Name.getAsIdentifierInfo(), 2973 cast_or_null<CXXRecordDecl>(PrevDecl))) 2974 return D2CXX; 2975 } 2976 2977 D2 = D2CXX; 2978 D2->setAccess(D->getAccess()); 2979 D2->setLexicalDeclContext(LexicalDC); 2980 addDeclToContexts(D, D2); 2981 2982 if (ClassTemplateDecl *FromDescribed = 2983 DCXX->getDescribedClassTemplate()) { 2984 ClassTemplateDecl *ToDescribed; 2985 if (Error Err = importInto(ToDescribed, FromDescribed)) 2986 return std::move(Err); 2987 D2CXX->setDescribedClassTemplate(ToDescribed); 2988 if (!DCXX->isInjectedClassName() && !IsFriendTemplate) { 2989 // In a record describing a template the type should be an 2990 // InjectedClassNameType (see Sema::CheckClassTemplate). Update the 2991 // previously set type to the correct value here (ToDescribed is not 2992 // available at record create). 2993 CXXRecordDecl *Injected = nullptr; 2994 for (NamedDecl *Found : D2CXX->noload_lookup(Name)) { 2995 auto *Record = dyn_cast<CXXRecordDecl>(Found); 2996 if (Record && Record->isInjectedClassName()) { 2997 Injected = Record; 2998 break; 2999 } 3000 } 3001 // Create an injected type for the whole redecl chain. 3002 // The chain may contain an already existing injected type at the start, 3003 // if yes this should be reused. We must ensure that only one type 3004 // object exists for the injected type (including the injected record 3005 // declaration), ASTContext does not check it. 3006 SmallVector<Decl *, 2> Redecls = 3007 getCanonicalForwardRedeclChain(D2CXX); 3008 const Type *FrontTy = 3009 cast<CXXRecordDecl>(Redecls.front())->getTypeForDecl(); 3010 QualType InjSpec; 3011 if (auto *InjTy = FrontTy->getAs<InjectedClassNameType>()) 3012 InjSpec = InjTy->getInjectedSpecializationType(); 3013 else 3014 InjSpec = ToDescribed->getInjectedClassNameSpecialization(); 3015 for (auto *R : Redecls) { 3016 auto *RI = cast<CXXRecordDecl>(R); 3017 if (R != Redecls.front() || 3018 !isa<InjectedClassNameType>(RI->getTypeForDecl())) 3019 RI->setTypeForDecl(nullptr); 3020 // This function tries to get the injected type from getTypeForDecl, 3021 // then from the previous declaration if possible. If not, it creates 3022 // a new type. 3023 Importer.getToContext().getInjectedClassNameType(RI, InjSpec); 3024 } 3025 // Set the new type for the injected decl too. 3026 if (Injected) { 3027 Injected->setTypeForDecl(nullptr); 3028 // This function will copy the injected type from D2CXX into Injected. 3029 // The injected decl does not have a previous decl to copy from. 3030 Importer.getToContext().getTypeDeclType(Injected, D2CXX); 3031 } 3032 } 3033 } else if (MemberSpecializationInfo *MemberInfo = 3034 DCXX->getMemberSpecializationInfo()) { 3035 TemplateSpecializationKind SK = 3036 MemberInfo->getTemplateSpecializationKind(); 3037 CXXRecordDecl *FromInst = DCXX->getInstantiatedFromMemberClass(); 3038 3039 if (Expected<CXXRecordDecl *> ToInstOrErr = import(FromInst)) 3040 D2CXX->setInstantiationOfMemberClass(*ToInstOrErr, SK); 3041 else 3042 return ToInstOrErr.takeError(); 3043 3044 if (ExpectedSLoc POIOrErr = 3045 import(MemberInfo->getPointOfInstantiation())) 3046 D2CXX->getMemberSpecializationInfo()->setPointOfInstantiation( 3047 *POIOrErr); 3048 else 3049 return POIOrErr.takeError(); 3050 } 3051 3052 } else { 3053 if (GetImportedOrCreateDecl(D2, D, Importer.getToContext(), 3054 D->getTagKind(), DC, *BeginLocOrErr, Loc, 3055 Name.getAsIdentifierInfo(), PrevDecl)) 3056 return D2; 3057 D2->setLexicalDeclContext(LexicalDC); 3058 addDeclToContexts(D, D2); 3059 } 3060 3061 if (auto BraceRangeOrErr = import(D->getBraceRange())) 3062 D2->setBraceRange(*BraceRangeOrErr); 3063 else 3064 return BraceRangeOrErr.takeError(); 3065 if (auto QualifierLocOrErr = import(D->getQualifierLoc())) 3066 D2->setQualifierInfo(*QualifierLocOrErr); 3067 else 3068 return QualifierLocOrErr.takeError(); 3069 3070 if (D->isAnonymousStructOrUnion()) 3071 D2->setAnonymousStructOrUnion(true); 3072 3073 if (D->isCompleteDefinition()) 3074 if (Error Err = ImportDefinition(D, D2, IDK_Default)) 3075 return std::move(Err); 3076 3077 return D2; 3078 } 3079 3080 ExpectedDecl ASTNodeImporter::VisitEnumConstantDecl(EnumConstantDecl *D) { 3081 // Import the major distinguishing characteristics of this enumerator. 3082 DeclContext *DC, *LexicalDC; 3083 DeclarationName Name; 3084 SourceLocation Loc; 3085 NamedDecl *ToD; 3086 if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc)) 3087 return std::move(Err); 3088 if (ToD) 3089 return ToD; 3090 3091 // Determine whether there are any other declarations with the same name and 3092 // in the same context. 3093 if (!LexicalDC->isFunctionOrMethod()) { 3094 SmallVector<NamedDecl *, 4> ConflictingDecls; 3095 unsigned IDNS = Decl::IDNS_Ordinary; 3096 auto FoundDecls = Importer.findDeclsInToCtx(DC, Name); 3097 for (auto *FoundDecl : FoundDecls) { 3098 if (!FoundDecl->isInIdentifierNamespace(IDNS)) 3099 continue; 3100 3101 if (auto *FoundEnumConstant = dyn_cast<EnumConstantDecl>(FoundDecl)) { 3102 if (IsStructuralMatch(D, FoundEnumConstant)) 3103 return Importer.MapImported(D, FoundEnumConstant); 3104 ConflictingDecls.push_back(FoundDecl); 3105 } 3106 } 3107 3108 if (!ConflictingDecls.empty()) { 3109 ExpectedName NameOrErr = Importer.HandleNameConflict( 3110 Name, DC, IDNS, ConflictingDecls.data(), ConflictingDecls.size()); 3111 if (NameOrErr) 3112 Name = NameOrErr.get(); 3113 else 3114 return NameOrErr.takeError(); 3115 } 3116 } 3117 3118 ExpectedType TypeOrErr = import(D->getType()); 3119 if (!TypeOrErr) 3120 return TypeOrErr.takeError(); 3121 3122 ExpectedExpr InitOrErr = import(D->getInitExpr()); 3123 if (!InitOrErr) 3124 return InitOrErr.takeError(); 3125 3126 EnumConstantDecl *ToEnumerator; 3127 if (GetImportedOrCreateDecl( 3128 ToEnumerator, D, Importer.getToContext(), cast<EnumDecl>(DC), Loc, 3129 Name.getAsIdentifierInfo(), *TypeOrErr, *InitOrErr, D->getInitVal())) 3130 return ToEnumerator; 3131 3132 ToEnumerator->setAccess(D->getAccess()); 3133 ToEnumerator->setLexicalDeclContext(LexicalDC); 3134 LexicalDC->addDeclInternal(ToEnumerator); 3135 return ToEnumerator; 3136 } 3137 3138 Error ASTNodeImporter::ImportTemplateParameterLists(const DeclaratorDecl *FromD, 3139 DeclaratorDecl *ToD) { 3140 unsigned int Num = FromD->getNumTemplateParameterLists(); 3141 if (Num == 0) 3142 return Error::success(); 3143 SmallVector<TemplateParameterList *, 2> ToTPLists(Num); 3144 for (unsigned int I = 0; I < Num; ++I) 3145 if (Expected<TemplateParameterList *> ToTPListOrErr = 3146 import(FromD->getTemplateParameterList(I))) 3147 ToTPLists[I] = *ToTPListOrErr; 3148 else 3149 return ToTPListOrErr.takeError(); 3150 ToD->setTemplateParameterListsInfo(Importer.ToContext, ToTPLists); 3151 return Error::success(); 3152 } 3153 3154 Error ASTNodeImporter::ImportTemplateInformation( 3155 FunctionDecl *FromFD, FunctionDecl *ToFD) { 3156 switch (FromFD->getTemplatedKind()) { 3157 case FunctionDecl::TK_NonTemplate: 3158 case FunctionDecl::TK_FunctionTemplate: 3159 return Error::success(); 3160 3161 case FunctionDecl::TK_DependentNonTemplate: 3162 if (Expected<FunctionDecl *> InstFDOrErr = 3163 import(FromFD->getInstantiatedFromDecl())) 3164 ToFD->setInstantiatedFromDecl(*InstFDOrErr); 3165 return Error::success(); 3166 case FunctionDecl::TK_MemberSpecialization: { 3167 TemplateSpecializationKind TSK = FromFD->getTemplateSpecializationKind(); 3168 3169 if (Expected<FunctionDecl *> InstFDOrErr = 3170 import(FromFD->getInstantiatedFromMemberFunction())) 3171 ToFD->setInstantiationOfMemberFunction(*InstFDOrErr, TSK); 3172 else 3173 return InstFDOrErr.takeError(); 3174 3175 if (ExpectedSLoc POIOrErr = import( 3176 FromFD->getMemberSpecializationInfo()->getPointOfInstantiation())) 3177 ToFD->getMemberSpecializationInfo()->setPointOfInstantiation(*POIOrErr); 3178 else 3179 return POIOrErr.takeError(); 3180 3181 return Error::success(); 3182 } 3183 3184 case FunctionDecl::TK_FunctionTemplateSpecialization: { 3185 auto FunctionAndArgsOrErr = 3186 ImportFunctionTemplateWithTemplateArgsFromSpecialization(FromFD); 3187 if (!FunctionAndArgsOrErr) 3188 return FunctionAndArgsOrErr.takeError(); 3189 3190 TemplateArgumentList *ToTAList = TemplateArgumentList::CreateCopy( 3191 Importer.getToContext(), std::get<1>(*FunctionAndArgsOrErr)); 3192 3193 auto *FTSInfo = FromFD->getTemplateSpecializationInfo(); 3194 TemplateArgumentListInfo ToTAInfo; 3195 const auto *FromTAArgsAsWritten = FTSInfo->TemplateArgumentsAsWritten; 3196 if (FromTAArgsAsWritten) 3197 if (Error Err = ImportTemplateArgumentListInfo( 3198 *FromTAArgsAsWritten, ToTAInfo)) 3199 return Err; 3200 3201 ExpectedSLoc POIOrErr = import(FTSInfo->getPointOfInstantiation()); 3202 if (!POIOrErr) 3203 return POIOrErr.takeError(); 3204 3205 if (Error Err = ImportTemplateParameterLists(FromFD, ToFD)) 3206 return Err; 3207 3208 TemplateSpecializationKind TSK = FTSInfo->getTemplateSpecializationKind(); 3209 ToFD->setFunctionTemplateSpecialization( 3210 std::get<0>(*FunctionAndArgsOrErr), ToTAList, /* InsertPos= */ nullptr, 3211 TSK, FromTAArgsAsWritten ? &ToTAInfo : nullptr, *POIOrErr); 3212 return Error::success(); 3213 } 3214 3215 case FunctionDecl::TK_DependentFunctionTemplateSpecialization: { 3216 auto *FromInfo = FromFD->getDependentSpecializationInfo(); 3217 UnresolvedSet<8> TemplDecls; 3218 unsigned NumTemplates = FromInfo->getNumTemplates(); 3219 for (unsigned I = 0; I < NumTemplates; I++) { 3220 if (Expected<FunctionTemplateDecl *> ToFTDOrErr = 3221 import(FromInfo->getTemplate(I))) 3222 TemplDecls.addDecl(*ToFTDOrErr); 3223 else 3224 return ToFTDOrErr.takeError(); 3225 } 3226 3227 // Import TemplateArgumentListInfo. 3228 TemplateArgumentListInfo ToTAInfo; 3229 if (Error Err = ImportTemplateArgumentListInfo( 3230 FromInfo->getLAngleLoc(), FromInfo->getRAngleLoc(), 3231 llvm::ArrayRef(FromInfo->getTemplateArgs(), 3232 FromInfo->getNumTemplateArgs()), 3233 ToTAInfo)) 3234 return Err; 3235 3236 ToFD->setDependentTemplateSpecialization(Importer.getToContext(), 3237 TemplDecls, ToTAInfo); 3238 return Error::success(); 3239 } 3240 } 3241 llvm_unreachable("All cases should be covered!"); 3242 } 3243 3244 Expected<FunctionDecl *> 3245 ASTNodeImporter::FindFunctionTemplateSpecialization(FunctionDecl *FromFD) { 3246 auto FunctionAndArgsOrErr = 3247 ImportFunctionTemplateWithTemplateArgsFromSpecialization(FromFD); 3248 if (!FunctionAndArgsOrErr) 3249 return FunctionAndArgsOrErr.takeError(); 3250 3251 FunctionTemplateDecl *Template; 3252 TemplateArgsTy ToTemplArgs; 3253 std::tie(Template, ToTemplArgs) = *FunctionAndArgsOrErr; 3254 void *InsertPos = nullptr; 3255 auto *FoundSpec = Template->findSpecialization(ToTemplArgs, InsertPos); 3256 return FoundSpec; 3257 } 3258 3259 Error ASTNodeImporter::ImportFunctionDeclBody(FunctionDecl *FromFD, 3260 FunctionDecl *ToFD) { 3261 if (Stmt *FromBody = FromFD->getBody()) { 3262 if (ExpectedStmt ToBodyOrErr = import(FromBody)) 3263 ToFD->setBody(*ToBodyOrErr); 3264 else 3265 return ToBodyOrErr.takeError(); 3266 } 3267 return Error::success(); 3268 } 3269 3270 // Returns true if the given D has a DeclContext up to the TranslationUnitDecl 3271 // which is equal to the given DC, or D is equal to DC. 3272 static bool isAncestorDeclContextOf(const DeclContext *DC, const Decl *D) { 3273 const DeclContext *DCi = dyn_cast<DeclContext>(D); 3274 if (!DCi) 3275 DCi = D->getDeclContext(); 3276 assert(DCi && "Declaration should have a context"); 3277 while (DCi != D->getTranslationUnitDecl()) { 3278 if (DCi == DC) 3279 return true; 3280 DCi = DCi->getParent(); 3281 } 3282 return false; 3283 } 3284 3285 // Check if there is a declaration that has 'DC' as parent context and is 3286 // referenced from statement 'S' or one of its children. The search is done in 3287 // BFS order through children of 'S'. 3288 static bool isAncestorDeclContextOf(const DeclContext *DC, const Stmt *S) { 3289 SmallVector<const Stmt *> ToProcess; 3290 ToProcess.push_back(S); 3291 while (!ToProcess.empty()) { 3292 const Stmt *CurrentS = ToProcess.pop_back_val(); 3293 ToProcess.append(CurrentS->child_begin(), CurrentS->child_end()); 3294 if (const auto *DeclRef = dyn_cast<DeclRefExpr>(CurrentS)) 3295 if (const Decl *D = DeclRef->getDecl()) 3296 if (isAncestorDeclContextOf(DC, D)) 3297 return true; 3298 } 3299 return false; 3300 } 3301 3302 namespace { 3303 /// Check if a type has any reference to a declaration that is inside the body 3304 /// of a function. 3305 /// The \c CheckType(QualType) function should be used to determine 3306 /// this property. 3307 /// 3308 /// The type visitor visits one type object only (not recursive). 3309 /// To find all referenced declarations we must discover all type objects until 3310 /// the canonical type is reached (walk over typedef and similar objects). This 3311 /// is done by loop over all "sugar" type objects. For every such type we must 3312 /// check all declarations that are referenced from it. For this check the 3313 /// visitor is used. In the visit functions all referenced declarations except 3314 /// the one that follows in the sugar chain (if any) must be checked. For this 3315 /// check the same visitor is re-used (it has no state-dependent data). 3316 /// 3317 /// The visit functions have 3 possible return values: 3318 /// - True, found a declaration inside \c ParentDC. 3319 /// - False, found declarations only outside \c ParentDC and it is not possible 3320 /// to find more declarations (the "sugar" chain does not continue). 3321 /// - Empty optional value, found no declarations or only outside \c ParentDC, 3322 /// but it is possible to find more declarations in the type "sugar" chain. 3323 /// The loop over the "sugar" types can be implemented by using type visit 3324 /// functions only (call \c CheckType with the desugared type). With the current 3325 /// solution no visit function is needed if the type has only a desugared type 3326 /// as data. 3327 class IsTypeDeclaredInsideVisitor 3328 : public TypeVisitor<IsTypeDeclaredInsideVisitor, std::optional<bool>> { 3329 public: 3330 IsTypeDeclaredInsideVisitor(const FunctionDecl *ParentDC) 3331 : ParentDC(ParentDC) {} 3332 3333 bool CheckType(QualType T) { 3334 // Check the chain of "sugar" types. 3335 // The "sugar" types are typedef or similar types that have the same 3336 // canonical type. 3337 if (std::optional<bool> Res = Visit(T.getTypePtr())) 3338 return *Res; 3339 QualType DsT = 3340 T.getSingleStepDesugaredType(ParentDC->getParentASTContext()); 3341 while (DsT != T) { 3342 if (std::optional<bool> Res = Visit(DsT.getTypePtr())) 3343 return *Res; 3344 T = DsT; 3345 DsT = T.getSingleStepDesugaredType(ParentDC->getParentASTContext()); 3346 } 3347 return false; 3348 } 3349 3350 std::optional<bool> VisitTagType(const TagType *T) { 3351 if (auto *Spec = dyn_cast<ClassTemplateSpecializationDecl>(T->getDecl())) 3352 for (const auto &Arg : Spec->getTemplateArgs().asArray()) 3353 if (checkTemplateArgument(Arg)) 3354 return true; 3355 return isAncestorDeclContextOf(ParentDC, T->getDecl()); 3356 } 3357 3358 std::optional<bool> VisitPointerType(const PointerType *T) { 3359 return CheckType(T->getPointeeType()); 3360 } 3361 3362 std::optional<bool> VisitReferenceType(const ReferenceType *T) { 3363 return CheckType(T->getPointeeTypeAsWritten()); 3364 } 3365 3366 std::optional<bool> VisitTypedefType(const TypedefType *T) { 3367 const TypedefNameDecl *TD = T->getDecl(); 3368 assert(TD); 3369 return isAncestorDeclContextOf(ParentDC, TD); 3370 } 3371 3372 std::optional<bool> VisitUsingType(const UsingType *T) { 3373 if (T->getFoundDecl() && 3374 isAncestorDeclContextOf(ParentDC, T->getFoundDecl())) 3375 return true; 3376 3377 return {}; 3378 } 3379 3380 std::optional<bool> 3381 VisitTemplateSpecializationType(const TemplateSpecializationType *T) { 3382 for (const auto &Arg : T->template_arguments()) 3383 if (checkTemplateArgument(Arg)) 3384 return true; 3385 // This type is a "sugar" to a record type, it can have a desugared type. 3386 return {}; 3387 } 3388 3389 std::optional<bool> VisitConstantArrayType(const ConstantArrayType *T) { 3390 if (T->getSizeExpr() && isAncestorDeclContextOf(ParentDC, T->getSizeExpr())) 3391 return true; 3392 3393 return CheckType(T->getElementType()); 3394 } 3395 3396 std::optional<bool> VisitVariableArrayType(const VariableArrayType *T) { 3397 llvm_unreachable( 3398 "Variable array should not occur in deduced return type of a function"); 3399 } 3400 3401 std::optional<bool> VisitIncompleteArrayType(const IncompleteArrayType *T) { 3402 llvm_unreachable("Incomplete array should not occur in deduced return type " 3403 "of a function"); 3404 } 3405 3406 std::optional<bool> VisitDependentArrayType(const IncompleteArrayType *T) { 3407 llvm_unreachable("Dependent array should not occur in deduced return type " 3408 "of a function"); 3409 } 3410 3411 private: 3412 const DeclContext *const ParentDC; 3413 3414 bool checkTemplateArgument(const TemplateArgument &Arg) { 3415 switch (Arg.getKind()) { 3416 case TemplateArgument::Null: 3417 return false; 3418 case TemplateArgument::Integral: 3419 return CheckType(Arg.getIntegralType()); 3420 case TemplateArgument::Type: 3421 return CheckType(Arg.getAsType()); 3422 case TemplateArgument::Expression: 3423 return isAncestorDeclContextOf(ParentDC, Arg.getAsExpr()); 3424 case TemplateArgument::Declaration: 3425 // FIXME: The declaration in this case is not allowed to be in a function? 3426 return isAncestorDeclContextOf(ParentDC, Arg.getAsDecl()); 3427 case TemplateArgument::NullPtr: 3428 // FIXME: The type is not allowed to be in the function? 3429 return CheckType(Arg.getNullPtrType()); 3430 case TemplateArgument::Pack: 3431 for (const auto &PackArg : Arg.getPackAsArray()) 3432 if (checkTemplateArgument(PackArg)) 3433 return true; 3434 return false; 3435 case TemplateArgument::Template: 3436 // Templates can not be defined locally in functions. 3437 // A template passed as argument can be not in ParentDC. 3438 return false; 3439 case TemplateArgument::TemplateExpansion: 3440 // Templates can not be defined locally in functions. 3441 // A template passed as argument can be not in ParentDC. 3442 return false; 3443 } 3444 llvm_unreachable("Unknown TemplateArgument::ArgKind enum"); 3445 }; 3446 }; 3447 } // namespace 3448 3449 bool ASTNodeImporter::hasAutoReturnTypeDeclaredInside(FunctionDecl *D) { 3450 QualType FromTy = D->getType(); 3451 const auto *FromFPT = FromTy->getAs<FunctionProtoType>(); 3452 assert(FromFPT && "Must be called on FunctionProtoType"); 3453 3454 QualType RetT = FromFPT->getReturnType(); 3455 if (isa<AutoType>(RetT.getTypePtr())) { 3456 FunctionDecl *Def = D->getDefinition(); 3457 IsTypeDeclaredInsideVisitor Visitor(Def ? Def : D); 3458 return Visitor.CheckType(RetT); 3459 } 3460 3461 return false; 3462 } 3463 3464 ExplicitSpecifier 3465 ASTNodeImporter::importExplicitSpecifier(Error &Err, ExplicitSpecifier ESpec) { 3466 Expr *ExplicitExpr = ESpec.getExpr(); 3467 if (ExplicitExpr) 3468 ExplicitExpr = importChecked(Err, ESpec.getExpr()); 3469 return ExplicitSpecifier(ExplicitExpr, ESpec.getKind()); 3470 } 3471 3472 ExpectedDecl ASTNodeImporter::VisitFunctionDecl(FunctionDecl *D) { 3473 3474 SmallVector<Decl *, 2> Redecls = getCanonicalForwardRedeclChain(D); 3475 auto RedeclIt = Redecls.begin(); 3476 // Import the first part of the decl chain. I.e. import all previous 3477 // declarations starting from the canonical decl. 3478 for (; RedeclIt != Redecls.end() && *RedeclIt != D; ++RedeclIt) { 3479 ExpectedDecl ToRedeclOrErr = import(*RedeclIt); 3480 if (!ToRedeclOrErr) 3481 return ToRedeclOrErr.takeError(); 3482 } 3483 assert(*RedeclIt == D); 3484 3485 // Import the major distinguishing characteristics of this function. 3486 DeclContext *DC, *LexicalDC; 3487 DeclarationName Name; 3488 SourceLocation Loc; 3489 NamedDecl *ToD; 3490 if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc)) 3491 return std::move(Err); 3492 if (ToD) 3493 return ToD; 3494 3495 FunctionDecl *FoundByLookup = nullptr; 3496 FunctionTemplateDecl *FromFT = D->getDescribedFunctionTemplate(); 3497 3498 // If this is a function template specialization, then try to find the same 3499 // existing specialization in the "to" context. The lookup below will not 3500 // find any specialization, but would find the primary template; thus, we 3501 // have to skip normal lookup in case of specializations. 3502 // FIXME handle member function templates (TK_MemberSpecialization) similarly? 3503 if (D->getTemplatedKind() == 3504 FunctionDecl::TK_FunctionTemplateSpecialization) { 3505 auto FoundFunctionOrErr = FindFunctionTemplateSpecialization(D); 3506 if (!FoundFunctionOrErr) 3507 return FoundFunctionOrErr.takeError(); 3508 if (FunctionDecl *FoundFunction = *FoundFunctionOrErr) { 3509 if (Decl *Def = FindAndMapDefinition(D, FoundFunction)) 3510 return Def; 3511 FoundByLookup = FoundFunction; 3512 } 3513 } 3514 // Try to find a function in our own ("to") context with the same name, same 3515 // type, and in the same context as the function we're importing. 3516 else if (!LexicalDC->isFunctionOrMethod()) { 3517 SmallVector<NamedDecl *, 4> ConflictingDecls; 3518 unsigned IDNS = Decl::IDNS_Ordinary | Decl::IDNS_OrdinaryFriend; 3519 auto FoundDecls = Importer.findDeclsInToCtx(DC, Name); 3520 for (auto *FoundDecl : FoundDecls) { 3521 if (!FoundDecl->isInIdentifierNamespace(IDNS)) 3522 continue; 3523 3524 if (auto *FoundFunction = dyn_cast<FunctionDecl>(FoundDecl)) { 3525 if (!hasSameVisibilityContextAndLinkage(FoundFunction, D)) 3526 continue; 3527 3528 if (IsStructuralMatch(D, FoundFunction)) { 3529 if (Decl *Def = FindAndMapDefinition(D, FoundFunction)) 3530 return Def; 3531 FoundByLookup = FoundFunction; 3532 break; 3533 } 3534 // FIXME: Check for overloading more carefully, e.g., by boosting 3535 // Sema::IsOverload out to the AST library. 3536 3537 // Function overloading is okay in C++. 3538 if (Importer.getToContext().getLangOpts().CPlusPlus) 3539 continue; 3540 3541 // Complain about inconsistent function types. 3542 Importer.ToDiag(Loc, diag::warn_odr_function_type_inconsistent) 3543 << Name << D->getType() << FoundFunction->getType(); 3544 Importer.ToDiag(FoundFunction->getLocation(), diag::note_odr_value_here) 3545 << FoundFunction->getType(); 3546 ConflictingDecls.push_back(FoundDecl); 3547 } 3548 } 3549 3550 if (!ConflictingDecls.empty()) { 3551 ExpectedName NameOrErr = Importer.HandleNameConflict( 3552 Name, DC, IDNS, ConflictingDecls.data(), ConflictingDecls.size()); 3553 if (NameOrErr) 3554 Name = NameOrErr.get(); 3555 else 3556 return NameOrErr.takeError(); 3557 } 3558 } 3559 3560 // We do not allow more than one in-class declaration of a function. This is 3561 // because AST clients like VTableBuilder asserts on this. VTableBuilder 3562 // assumes there is only one in-class declaration. Building a redecl 3563 // chain would result in more than one in-class declaration for 3564 // overrides (even if they are part of the same redecl chain inside the 3565 // derived class.) 3566 if (FoundByLookup) { 3567 if (isa<CXXMethodDecl>(FoundByLookup)) { 3568 if (D->getLexicalDeclContext() == D->getDeclContext()) { 3569 if (!D->doesThisDeclarationHaveABody()) { 3570 if (FunctionTemplateDecl *DescribedD = 3571 D->getDescribedFunctionTemplate()) { 3572 // Handle a "templated" function together with its described 3573 // template. This avoids need for a similar check at import of the 3574 // described template. 3575 assert(FoundByLookup->getDescribedFunctionTemplate() && 3576 "Templated function mapped to non-templated?"); 3577 Importer.MapImported(DescribedD, 3578 FoundByLookup->getDescribedFunctionTemplate()); 3579 } 3580 return Importer.MapImported(D, FoundByLookup); 3581 } else { 3582 // Let's continue and build up the redecl chain in this case. 3583 // FIXME Merge the functions into one decl. 3584 } 3585 } 3586 } 3587 } 3588 3589 DeclarationNameInfo NameInfo(Name, Loc); 3590 // Import additional name location/type info. 3591 if (Error Err = ImportDeclarationNameLoc(D->getNameInfo(), NameInfo)) 3592 return std::move(Err); 3593 3594 QualType FromTy = D->getType(); 3595 TypeSourceInfo *FromTSI = D->getTypeSourceInfo(); 3596 // Set to true if we do not import the type of the function as is. There are 3597 // cases when the original type would result in an infinite recursion during 3598 // the import. To avoid an infinite recursion when importing, we create the 3599 // FunctionDecl with a simplified function type and update it only after the 3600 // relevant AST nodes are already imported. 3601 // The type is related to TypeSourceInfo (it references the type), so we must 3602 // do the same with TypeSourceInfo. 3603 bool UsedDifferentProtoType = false; 3604 if (const auto *FromFPT = FromTy->getAs<FunctionProtoType>()) { 3605 QualType FromReturnTy = FromFPT->getReturnType(); 3606 // Functions with auto return type may define a struct inside their body 3607 // and the return type could refer to that struct. 3608 // E.g.: auto foo() { struct X{}; return X(); } 3609 // To avoid an infinite recursion when importing, create the FunctionDecl 3610 // with a simplified return type. 3611 if (hasAutoReturnTypeDeclaredInside(D)) { 3612 FromReturnTy = Importer.getFromContext().VoidTy; 3613 UsedDifferentProtoType = true; 3614 } 3615 FunctionProtoType::ExtProtoInfo FromEPI = FromFPT->getExtProtoInfo(); 3616 // FunctionProtoType::ExtProtoInfo's ExceptionSpecDecl can point to the 3617 // FunctionDecl that we are importing the FunctionProtoType for. 3618 // To avoid an infinite recursion when importing, create the FunctionDecl 3619 // with a simplified function type. 3620 if (FromEPI.ExceptionSpec.SourceDecl || 3621 FromEPI.ExceptionSpec.SourceTemplate || 3622 FromEPI.ExceptionSpec.NoexceptExpr) { 3623 FunctionProtoType::ExtProtoInfo DefaultEPI; 3624 FromEPI = DefaultEPI; 3625 UsedDifferentProtoType = true; 3626 } 3627 FromTy = Importer.getFromContext().getFunctionType( 3628 FromReturnTy, FromFPT->getParamTypes(), FromEPI); 3629 FromTSI = Importer.getFromContext().getTrivialTypeSourceInfo( 3630 FromTy, D->getBeginLoc()); 3631 } 3632 3633 Error Err = Error::success(); 3634 auto T = importChecked(Err, FromTy); 3635 auto TInfo = importChecked(Err, FromTSI); 3636 auto ToInnerLocStart = importChecked(Err, D->getInnerLocStart()); 3637 auto ToEndLoc = importChecked(Err, D->getEndLoc()); 3638 auto ToDefaultLoc = importChecked(Err, D->getDefaultLoc()); 3639 auto ToQualifierLoc = importChecked(Err, D->getQualifierLoc()); 3640 auto TrailingRequiresClause = 3641 importChecked(Err, D->getTrailingRequiresClause()); 3642 if (Err) 3643 return std::move(Err); 3644 3645 // Import the function parameters. 3646 SmallVector<ParmVarDecl *, 8> Parameters; 3647 for (auto *P : D->parameters()) { 3648 if (Expected<ParmVarDecl *> ToPOrErr = import(P)) 3649 Parameters.push_back(*ToPOrErr); 3650 else 3651 return ToPOrErr.takeError(); 3652 } 3653 3654 // Create the imported function. 3655 FunctionDecl *ToFunction = nullptr; 3656 if (auto *FromConstructor = dyn_cast<CXXConstructorDecl>(D)) { 3657 ExplicitSpecifier ESpec = 3658 importExplicitSpecifier(Err, FromConstructor->getExplicitSpecifier()); 3659 if (Err) 3660 return std::move(Err); 3661 auto ToInheritedConstructor = InheritedConstructor(); 3662 if (FromConstructor->isInheritingConstructor()) { 3663 Expected<InheritedConstructor> ImportedInheritedCtor = 3664 import(FromConstructor->getInheritedConstructor()); 3665 if (!ImportedInheritedCtor) 3666 return ImportedInheritedCtor.takeError(); 3667 ToInheritedConstructor = *ImportedInheritedCtor; 3668 } 3669 if (GetImportedOrCreateDecl<CXXConstructorDecl>( 3670 ToFunction, D, Importer.getToContext(), cast<CXXRecordDecl>(DC), 3671 ToInnerLocStart, NameInfo, T, TInfo, ESpec, D->UsesFPIntrin(), 3672 D->isInlineSpecified(), D->isImplicit(), D->getConstexprKind(), 3673 ToInheritedConstructor, TrailingRequiresClause)) 3674 return ToFunction; 3675 } else if (CXXDestructorDecl *FromDtor = dyn_cast<CXXDestructorDecl>(D)) { 3676 3677 Error Err = Error::success(); 3678 auto ToOperatorDelete = importChecked( 3679 Err, const_cast<FunctionDecl *>(FromDtor->getOperatorDelete())); 3680 auto ToThisArg = importChecked(Err, FromDtor->getOperatorDeleteThisArg()); 3681 if (Err) 3682 return std::move(Err); 3683 3684 if (GetImportedOrCreateDecl<CXXDestructorDecl>( 3685 ToFunction, D, Importer.getToContext(), cast<CXXRecordDecl>(DC), 3686 ToInnerLocStart, NameInfo, T, TInfo, D->UsesFPIntrin(), 3687 D->isInlineSpecified(), D->isImplicit(), D->getConstexprKind(), 3688 TrailingRequiresClause)) 3689 return ToFunction; 3690 3691 CXXDestructorDecl *ToDtor = cast<CXXDestructorDecl>(ToFunction); 3692 3693 ToDtor->setOperatorDelete(ToOperatorDelete, ToThisArg); 3694 } else if (CXXConversionDecl *FromConversion = 3695 dyn_cast<CXXConversionDecl>(D)) { 3696 ExplicitSpecifier ESpec = 3697 importExplicitSpecifier(Err, FromConversion->getExplicitSpecifier()); 3698 if (Err) 3699 return std::move(Err); 3700 if (GetImportedOrCreateDecl<CXXConversionDecl>( 3701 ToFunction, D, Importer.getToContext(), cast<CXXRecordDecl>(DC), 3702 ToInnerLocStart, NameInfo, T, TInfo, D->UsesFPIntrin(), 3703 D->isInlineSpecified(), ESpec, D->getConstexprKind(), 3704 SourceLocation(), TrailingRequiresClause)) 3705 return ToFunction; 3706 } else if (auto *Method = dyn_cast<CXXMethodDecl>(D)) { 3707 if (GetImportedOrCreateDecl<CXXMethodDecl>( 3708 ToFunction, D, Importer.getToContext(), cast<CXXRecordDecl>(DC), 3709 ToInnerLocStart, NameInfo, T, TInfo, Method->getStorageClass(), 3710 Method->UsesFPIntrin(), Method->isInlineSpecified(), 3711 D->getConstexprKind(), SourceLocation(), TrailingRequiresClause)) 3712 return ToFunction; 3713 } else if (auto *Guide = dyn_cast<CXXDeductionGuideDecl>(D)) { 3714 ExplicitSpecifier ESpec = 3715 importExplicitSpecifier(Err, Guide->getExplicitSpecifier()); 3716 CXXConstructorDecl *Ctor = 3717 importChecked(Err, Guide->getCorrespondingConstructor()); 3718 if (Err) 3719 return std::move(Err); 3720 if (GetImportedOrCreateDecl<CXXDeductionGuideDecl>( 3721 ToFunction, D, Importer.getToContext(), DC, ToInnerLocStart, ESpec, 3722 NameInfo, T, TInfo, ToEndLoc, Ctor)) 3723 return ToFunction; 3724 cast<CXXDeductionGuideDecl>(ToFunction) 3725 ->setDeductionCandidateKind(Guide->getDeductionCandidateKind()); 3726 } else { 3727 if (GetImportedOrCreateDecl( 3728 ToFunction, D, Importer.getToContext(), DC, ToInnerLocStart, 3729 NameInfo, T, TInfo, D->getStorageClass(), D->UsesFPIntrin(), 3730 D->isInlineSpecified(), D->hasWrittenPrototype(), 3731 D->getConstexprKind(), TrailingRequiresClause)) 3732 return ToFunction; 3733 } 3734 3735 // Connect the redecl chain. 3736 if (FoundByLookup) { 3737 auto *Recent = const_cast<FunctionDecl *>( 3738 FoundByLookup->getMostRecentDecl()); 3739 ToFunction->setPreviousDecl(Recent); 3740 // FIXME Probably we should merge exception specifications. E.g. In the 3741 // "To" context the existing function may have exception specification with 3742 // noexcept-unevaluated, while the newly imported function may have an 3743 // evaluated noexcept. A call to adjustExceptionSpec() on the imported 3744 // decl and its redeclarations may be required. 3745 } 3746 3747 ToFunction->setQualifierInfo(ToQualifierLoc); 3748 ToFunction->setAccess(D->getAccess()); 3749 ToFunction->setLexicalDeclContext(LexicalDC); 3750 ToFunction->setVirtualAsWritten(D->isVirtualAsWritten()); 3751 ToFunction->setTrivial(D->isTrivial()); 3752 ToFunction->setPure(D->isPure()); 3753 ToFunction->setDefaulted(D->isDefaulted()); 3754 ToFunction->setExplicitlyDefaulted(D->isExplicitlyDefaulted()); 3755 ToFunction->setDeletedAsWritten(D->isDeletedAsWritten()); 3756 ToFunction->setFriendConstraintRefersToEnclosingTemplate( 3757 D->FriendConstraintRefersToEnclosingTemplate()); 3758 ToFunction->setRangeEnd(ToEndLoc); 3759 ToFunction->setDefaultLoc(ToDefaultLoc); 3760 3761 // Set the parameters. 3762 for (auto *Param : Parameters) { 3763 Param->setOwningFunction(ToFunction); 3764 ToFunction->addDeclInternal(Param); 3765 if (ASTImporterLookupTable *LT = Importer.SharedState->getLookupTable()) 3766 LT->update(Param, Importer.getToContext().getTranslationUnitDecl()); 3767 } 3768 ToFunction->setParams(Parameters); 3769 3770 // We need to complete creation of FunctionProtoTypeLoc manually with setting 3771 // params it refers to. 3772 if (TInfo) { 3773 if (auto ProtoLoc = 3774 TInfo->getTypeLoc().IgnoreParens().getAs<FunctionProtoTypeLoc>()) { 3775 for (unsigned I = 0, N = Parameters.size(); I != N; ++I) 3776 ProtoLoc.setParam(I, Parameters[I]); 3777 } 3778 } 3779 3780 // Import the describing template function, if any. 3781 if (FromFT) { 3782 auto ToFTOrErr = import(FromFT); 3783 if (!ToFTOrErr) 3784 return ToFTOrErr.takeError(); 3785 } 3786 3787 // Import Ctor initializers. 3788 if (auto *FromConstructor = dyn_cast<CXXConstructorDecl>(D)) { 3789 if (unsigned NumInitializers = FromConstructor->getNumCtorInitializers()) { 3790 SmallVector<CXXCtorInitializer *, 4> CtorInitializers(NumInitializers); 3791 // Import first, then allocate memory and copy if there was no error. 3792 if (Error Err = ImportContainerChecked( 3793 FromConstructor->inits(), CtorInitializers)) 3794 return std::move(Err); 3795 auto **Memory = 3796 new (Importer.getToContext()) CXXCtorInitializer *[NumInitializers]; 3797 std::copy(CtorInitializers.begin(), CtorInitializers.end(), Memory); 3798 auto *ToCtor = cast<CXXConstructorDecl>(ToFunction); 3799 ToCtor->setCtorInitializers(Memory); 3800 ToCtor->setNumCtorInitializers(NumInitializers); 3801 } 3802 } 3803 3804 // If it is a template, import all related things. 3805 if (Error Err = ImportTemplateInformation(D, ToFunction)) 3806 return std::move(Err); 3807 3808 if (auto *FromCXXMethod = dyn_cast<CXXMethodDecl>(D)) 3809 if (Error Err = ImportOverriddenMethods(cast<CXXMethodDecl>(ToFunction), 3810 FromCXXMethod)) 3811 return std::move(Err); 3812 3813 if (D->doesThisDeclarationHaveABody()) { 3814 Error Err = ImportFunctionDeclBody(D, ToFunction); 3815 3816 if (Err) 3817 return std::move(Err); 3818 } 3819 3820 // Import and set the original type in case we used another type. 3821 if (UsedDifferentProtoType) { 3822 if (ExpectedType TyOrErr = import(D->getType())) 3823 ToFunction->setType(*TyOrErr); 3824 else 3825 return TyOrErr.takeError(); 3826 if (Expected<TypeSourceInfo *> TSIOrErr = import(D->getTypeSourceInfo())) 3827 ToFunction->setTypeSourceInfo(*TSIOrErr); 3828 else 3829 return TSIOrErr.takeError(); 3830 } 3831 3832 // FIXME: Other bits to merge? 3833 3834 addDeclToContexts(D, ToFunction); 3835 3836 // Import the rest of the chain. I.e. import all subsequent declarations. 3837 for (++RedeclIt; RedeclIt != Redecls.end(); ++RedeclIt) { 3838 ExpectedDecl ToRedeclOrErr = import(*RedeclIt); 3839 if (!ToRedeclOrErr) 3840 return ToRedeclOrErr.takeError(); 3841 } 3842 3843 return ToFunction; 3844 } 3845 3846 ExpectedDecl ASTNodeImporter::VisitCXXMethodDecl(CXXMethodDecl *D) { 3847 return VisitFunctionDecl(D); 3848 } 3849 3850 ExpectedDecl ASTNodeImporter::VisitCXXConstructorDecl(CXXConstructorDecl *D) { 3851 return VisitCXXMethodDecl(D); 3852 } 3853 3854 ExpectedDecl ASTNodeImporter::VisitCXXDestructorDecl(CXXDestructorDecl *D) { 3855 return VisitCXXMethodDecl(D); 3856 } 3857 3858 ExpectedDecl ASTNodeImporter::VisitCXXConversionDecl(CXXConversionDecl *D) { 3859 return VisitCXXMethodDecl(D); 3860 } 3861 3862 ExpectedDecl 3863 ASTNodeImporter::VisitCXXDeductionGuideDecl(CXXDeductionGuideDecl *D) { 3864 return VisitFunctionDecl(D); 3865 } 3866 3867 ExpectedDecl ASTNodeImporter::VisitFieldDecl(FieldDecl *D) { 3868 // Import the major distinguishing characteristics of a variable. 3869 DeclContext *DC, *LexicalDC; 3870 DeclarationName Name; 3871 SourceLocation Loc; 3872 NamedDecl *ToD; 3873 if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc)) 3874 return std::move(Err); 3875 if (ToD) 3876 return ToD; 3877 3878 // Determine whether we've already imported this field. 3879 auto FoundDecls = Importer.findDeclsInToCtx(DC, Name); 3880 for (auto *FoundDecl : FoundDecls) { 3881 if (FieldDecl *FoundField = dyn_cast<FieldDecl>(FoundDecl)) { 3882 // For anonymous fields, match up by index. 3883 if (!Name && 3884 ASTImporter::getFieldIndex(D) != 3885 ASTImporter::getFieldIndex(FoundField)) 3886 continue; 3887 3888 if (Importer.IsStructurallyEquivalent(D->getType(), 3889 FoundField->getType())) { 3890 Importer.MapImported(D, FoundField); 3891 // In case of a FieldDecl of a ClassTemplateSpecializationDecl, the 3892 // initializer of a FieldDecl might not had been instantiated in the 3893 // "To" context. However, the "From" context might instantiated that, 3894 // thus we have to merge that. 3895 // Note: `hasInClassInitializer()` is not the same as non-null 3896 // `getInClassInitializer()` value. 3897 if (Expr *FromInitializer = D->getInClassInitializer()) { 3898 if (ExpectedExpr ToInitializerOrErr = import(FromInitializer)) { 3899 // Import of the FromInitializer may result in the setting of 3900 // InClassInitializer. If not, set it here. 3901 assert(FoundField->hasInClassInitializer() && 3902 "Field should have an in-class initializer if it has an " 3903 "expression for it."); 3904 if (!FoundField->getInClassInitializer()) 3905 FoundField->setInClassInitializer(*ToInitializerOrErr); 3906 } else { 3907 return ToInitializerOrErr.takeError(); 3908 } 3909 } 3910 return FoundField; 3911 } 3912 3913 // FIXME: Why is this case not handled with calling HandleNameConflict? 3914 Importer.ToDiag(Loc, diag::warn_odr_field_type_inconsistent) 3915 << Name << D->getType() << FoundField->getType(); 3916 Importer.ToDiag(FoundField->getLocation(), diag::note_odr_value_here) 3917 << FoundField->getType(); 3918 3919 return make_error<ASTImportError>(ASTImportError::NameConflict); 3920 } 3921 } 3922 3923 Error Err = Error::success(); 3924 auto ToType = importChecked(Err, D->getType()); 3925 auto ToTInfo = importChecked(Err, D->getTypeSourceInfo()); 3926 auto ToBitWidth = importChecked(Err, D->getBitWidth()); 3927 auto ToInnerLocStart = importChecked(Err, D->getInnerLocStart()); 3928 auto ToInitializer = importChecked(Err, D->getInClassInitializer()); 3929 if (Err) 3930 return std::move(Err); 3931 const Type *ToCapturedVLAType = nullptr; 3932 if (Error Err = Importer.importInto( 3933 ToCapturedVLAType, cast_or_null<Type>(D->getCapturedVLAType()))) 3934 return std::move(Err); 3935 3936 FieldDecl *ToField; 3937 if (GetImportedOrCreateDecl(ToField, D, Importer.getToContext(), DC, 3938 ToInnerLocStart, Loc, Name.getAsIdentifierInfo(), 3939 ToType, ToTInfo, ToBitWidth, D->isMutable(), 3940 D->getInClassInitStyle())) 3941 return ToField; 3942 3943 // We need [[no_unqiue_address]] attributes to be added to FieldDecl, before 3944 // we add fields in CXXRecordDecl::addedMember, otherwise record will be 3945 // marked as having non-zero size. 3946 Err = Importer.ImportAttrs(ToField, D); 3947 if (Err) 3948 return std::move(Err); 3949 ToField->setAccess(D->getAccess()); 3950 ToField->setLexicalDeclContext(LexicalDC); 3951 if (ToInitializer) 3952 ToField->setInClassInitializer(ToInitializer); 3953 ToField->setImplicit(D->isImplicit()); 3954 if (ToCapturedVLAType) 3955 ToField->setCapturedVLAType(cast<VariableArrayType>(ToCapturedVLAType)); 3956 LexicalDC->addDeclInternal(ToField); 3957 return ToField; 3958 } 3959 3960 ExpectedDecl ASTNodeImporter::VisitIndirectFieldDecl(IndirectFieldDecl *D) { 3961 // Import the major distinguishing characteristics of a variable. 3962 DeclContext *DC, *LexicalDC; 3963 DeclarationName Name; 3964 SourceLocation Loc; 3965 NamedDecl *ToD; 3966 if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc)) 3967 return std::move(Err); 3968 if (ToD) 3969 return ToD; 3970 3971 // Determine whether we've already imported this field. 3972 auto FoundDecls = Importer.findDeclsInToCtx(DC, Name); 3973 for (unsigned I = 0, N = FoundDecls.size(); I != N; ++I) { 3974 if (auto *FoundField = dyn_cast<IndirectFieldDecl>(FoundDecls[I])) { 3975 // For anonymous indirect fields, match up by index. 3976 if (!Name && 3977 ASTImporter::getFieldIndex(D) != 3978 ASTImporter::getFieldIndex(FoundField)) 3979 continue; 3980 3981 if (Importer.IsStructurallyEquivalent(D->getType(), 3982 FoundField->getType(), 3983 !Name.isEmpty())) { 3984 Importer.MapImported(D, FoundField); 3985 return FoundField; 3986 } 3987 3988 // If there are more anonymous fields to check, continue. 3989 if (!Name && I < N-1) 3990 continue; 3991 3992 // FIXME: Why is this case not handled with calling HandleNameConflict? 3993 Importer.ToDiag(Loc, diag::warn_odr_field_type_inconsistent) 3994 << Name << D->getType() << FoundField->getType(); 3995 Importer.ToDiag(FoundField->getLocation(), diag::note_odr_value_here) 3996 << FoundField->getType(); 3997 3998 return make_error<ASTImportError>(ASTImportError::NameConflict); 3999 } 4000 } 4001 4002 // Import the type. 4003 auto TypeOrErr = import(D->getType()); 4004 if (!TypeOrErr) 4005 return TypeOrErr.takeError(); 4006 4007 auto **NamedChain = 4008 new (Importer.getToContext()) NamedDecl*[D->getChainingSize()]; 4009 4010 unsigned i = 0; 4011 for (auto *PI : D->chain()) 4012 if (Expected<NamedDecl *> ToD = import(PI)) 4013 NamedChain[i++] = *ToD; 4014 else 4015 return ToD.takeError(); 4016 4017 llvm::MutableArrayRef<NamedDecl *> CH = {NamedChain, D->getChainingSize()}; 4018 IndirectFieldDecl *ToIndirectField; 4019 if (GetImportedOrCreateDecl(ToIndirectField, D, Importer.getToContext(), DC, 4020 Loc, Name.getAsIdentifierInfo(), *TypeOrErr, CH)) 4021 // FIXME here we leak `NamedChain` which is allocated before 4022 return ToIndirectField; 4023 4024 ToIndirectField->setAccess(D->getAccess()); 4025 ToIndirectField->setLexicalDeclContext(LexicalDC); 4026 LexicalDC->addDeclInternal(ToIndirectField); 4027 return ToIndirectField; 4028 } 4029 4030 /// Used as return type of getFriendCountAndPosition. 4031 struct FriendCountAndPosition { 4032 /// Number of similar looking friends. 4033 unsigned int TotalCount; 4034 /// Index of the specific FriendDecl. 4035 unsigned int IndexOfDecl; 4036 }; 4037 4038 template <class T> 4039 static FriendCountAndPosition getFriendCountAndPosition( 4040 const FriendDecl *FD, 4041 llvm::function_ref<T(const FriendDecl *)> GetCanTypeOrDecl) { 4042 unsigned int FriendCount = 0; 4043 std::optional<unsigned int> FriendPosition; 4044 const auto *RD = cast<CXXRecordDecl>(FD->getLexicalDeclContext()); 4045 4046 T TypeOrDecl = GetCanTypeOrDecl(FD); 4047 4048 for (const FriendDecl *FoundFriend : RD->friends()) { 4049 if (FoundFriend == FD) { 4050 FriendPosition = FriendCount; 4051 ++FriendCount; 4052 } else if (!FoundFriend->getFriendDecl() == !FD->getFriendDecl() && 4053 GetCanTypeOrDecl(FoundFriend) == TypeOrDecl) { 4054 ++FriendCount; 4055 } 4056 } 4057 4058 assert(FriendPosition && "Friend decl not found in own parent."); 4059 4060 return {FriendCount, *FriendPosition}; 4061 } 4062 4063 static FriendCountAndPosition getFriendCountAndPosition(const FriendDecl *FD) { 4064 if (FD->getFriendType()) 4065 return getFriendCountAndPosition<QualType>(FD, [](const FriendDecl *F) { 4066 if (TypeSourceInfo *TSI = F->getFriendType()) 4067 return TSI->getType().getCanonicalType(); 4068 llvm_unreachable("Wrong friend object type."); 4069 }); 4070 else 4071 return getFriendCountAndPosition<Decl *>(FD, [](const FriendDecl *F) { 4072 if (Decl *D = F->getFriendDecl()) 4073 return D->getCanonicalDecl(); 4074 llvm_unreachable("Wrong friend object type."); 4075 }); 4076 } 4077 4078 ExpectedDecl ASTNodeImporter::VisitFriendDecl(FriendDecl *D) { 4079 // Import the major distinguishing characteristics of a declaration. 4080 DeclContext *DC, *LexicalDC; 4081 if (Error Err = ImportDeclContext(D, DC, LexicalDC)) 4082 return std::move(Err); 4083 4084 // Determine whether we've already imported this decl. 4085 // FriendDecl is not a NamedDecl so we cannot use lookup. 4086 // We try to maintain order and count of redundant friend declarations. 4087 const auto *RD = cast<CXXRecordDecl>(DC); 4088 FriendDecl *ImportedFriend = RD->getFirstFriend(); 4089 SmallVector<FriendDecl *, 2> ImportedEquivalentFriends; 4090 4091 while (ImportedFriend) { 4092 bool Match = false; 4093 if (D->getFriendDecl() && ImportedFriend->getFriendDecl()) { 4094 Match = 4095 IsStructuralMatch(D->getFriendDecl(), ImportedFriend->getFriendDecl(), 4096 /*Complain=*/false); 4097 } else if (D->getFriendType() && ImportedFriend->getFriendType()) { 4098 Match = Importer.IsStructurallyEquivalent( 4099 D->getFriendType()->getType(), 4100 ImportedFriend->getFriendType()->getType(), /*Complain=*/false); 4101 } 4102 if (Match) 4103 ImportedEquivalentFriends.push_back(ImportedFriend); 4104 4105 ImportedFriend = ImportedFriend->getNextFriend(); 4106 } 4107 FriendCountAndPosition CountAndPosition = getFriendCountAndPosition(D); 4108 4109 assert(ImportedEquivalentFriends.size() <= CountAndPosition.TotalCount && 4110 "Class with non-matching friends is imported, ODR check wrong?"); 4111 if (ImportedEquivalentFriends.size() == CountAndPosition.TotalCount) 4112 return Importer.MapImported( 4113 D, ImportedEquivalentFriends[CountAndPosition.IndexOfDecl]); 4114 4115 // Not found. Create it. 4116 // The declarations will be put into order later by ImportDeclContext. 4117 FriendDecl::FriendUnion ToFU; 4118 if (NamedDecl *FriendD = D->getFriendDecl()) { 4119 NamedDecl *ToFriendD; 4120 if (Error Err = importInto(ToFriendD, FriendD)) 4121 return std::move(Err); 4122 4123 if (FriendD->getFriendObjectKind() != Decl::FOK_None && 4124 !(FriendD->isInIdentifierNamespace(Decl::IDNS_NonMemberOperator))) 4125 ToFriendD->setObjectOfFriendDecl(false); 4126 4127 ToFU = ToFriendD; 4128 } else { // The friend is a type, not a decl. 4129 if (auto TSIOrErr = import(D->getFriendType())) 4130 ToFU = *TSIOrErr; 4131 else 4132 return TSIOrErr.takeError(); 4133 } 4134 4135 SmallVector<TemplateParameterList *, 1> ToTPLists(D->NumTPLists); 4136 auto **FromTPLists = D->getTrailingObjects<TemplateParameterList *>(); 4137 for (unsigned I = 0; I < D->NumTPLists; I++) { 4138 if (auto ListOrErr = import(FromTPLists[I])) 4139 ToTPLists[I] = *ListOrErr; 4140 else 4141 return ListOrErr.takeError(); 4142 } 4143 4144 auto LocationOrErr = import(D->getLocation()); 4145 if (!LocationOrErr) 4146 return LocationOrErr.takeError(); 4147 auto FriendLocOrErr = import(D->getFriendLoc()); 4148 if (!FriendLocOrErr) 4149 return FriendLocOrErr.takeError(); 4150 4151 FriendDecl *FrD; 4152 if (GetImportedOrCreateDecl(FrD, D, Importer.getToContext(), DC, 4153 *LocationOrErr, ToFU, 4154 *FriendLocOrErr, ToTPLists)) 4155 return FrD; 4156 4157 FrD->setAccess(D->getAccess()); 4158 FrD->setLexicalDeclContext(LexicalDC); 4159 LexicalDC->addDeclInternal(FrD); 4160 return FrD; 4161 } 4162 4163 ExpectedDecl ASTNodeImporter::VisitObjCIvarDecl(ObjCIvarDecl *D) { 4164 // Import the major distinguishing characteristics of an ivar. 4165 DeclContext *DC, *LexicalDC; 4166 DeclarationName Name; 4167 SourceLocation Loc; 4168 NamedDecl *ToD; 4169 if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc)) 4170 return std::move(Err); 4171 if (ToD) 4172 return ToD; 4173 4174 // Determine whether we've already imported this ivar 4175 auto FoundDecls = Importer.findDeclsInToCtx(DC, Name); 4176 for (auto *FoundDecl : FoundDecls) { 4177 if (ObjCIvarDecl *FoundIvar = dyn_cast<ObjCIvarDecl>(FoundDecl)) { 4178 if (Importer.IsStructurallyEquivalent(D->getType(), 4179 FoundIvar->getType())) { 4180 Importer.MapImported(D, FoundIvar); 4181 return FoundIvar; 4182 } 4183 4184 Importer.ToDiag(Loc, diag::warn_odr_ivar_type_inconsistent) 4185 << Name << D->getType() << FoundIvar->getType(); 4186 Importer.ToDiag(FoundIvar->getLocation(), diag::note_odr_value_here) 4187 << FoundIvar->getType(); 4188 4189 return make_error<ASTImportError>(ASTImportError::NameConflict); 4190 } 4191 } 4192 4193 Error Err = Error::success(); 4194 auto ToType = importChecked(Err, D->getType()); 4195 auto ToTypeSourceInfo = importChecked(Err, D->getTypeSourceInfo()); 4196 auto ToBitWidth = importChecked(Err, D->getBitWidth()); 4197 auto ToInnerLocStart = importChecked(Err, D->getInnerLocStart()); 4198 if (Err) 4199 return std::move(Err); 4200 4201 ObjCIvarDecl *ToIvar; 4202 if (GetImportedOrCreateDecl( 4203 ToIvar, D, Importer.getToContext(), cast<ObjCContainerDecl>(DC), 4204 ToInnerLocStart, Loc, Name.getAsIdentifierInfo(), 4205 ToType, ToTypeSourceInfo, 4206 D->getAccessControl(),ToBitWidth, D->getSynthesize())) 4207 return ToIvar; 4208 4209 ToIvar->setLexicalDeclContext(LexicalDC); 4210 LexicalDC->addDeclInternal(ToIvar); 4211 return ToIvar; 4212 } 4213 4214 ExpectedDecl ASTNodeImporter::VisitVarDecl(VarDecl *D) { 4215 4216 SmallVector<Decl*, 2> Redecls = getCanonicalForwardRedeclChain(D); 4217 auto RedeclIt = Redecls.begin(); 4218 // Import the first part of the decl chain. I.e. import all previous 4219 // declarations starting from the canonical decl. 4220 for (; RedeclIt != Redecls.end() && *RedeclIt != D; ++RedeclIt) { 4221 ExpectedDecl RedeclOrErr = import(*RedeclIt); 4222 if (!RedeclOrErr) 4223 return RedeclOrErr.takeError(); 4224 } 4225 assert(*RedeclIt == D); 4226 4227 // Import the major distinguishing characteristics of a variable. 4228 DeclContext *DC, *LexicalDC; 4229 DeclarationName Name; 4230 SourceLocation Loc; 4231 NamedDecl *ToD; 4232 if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc)) 4233 return std::move(Err); 4234 if (ToD) 4235 return ToD; 4236 4237 // Try to find a variable in our own ("to") context with the same name and 4238 // in the same context as the variable we're importing. 4239 VarDecl *FoundByLookup = nullptr; 4240 if (D->isFileVarDecl()) { 4241 SmallVector<NamedDecl *, 4> ConflictingDecls; 4242 unsigned IDNS = Decl::IDNS_Ordinary; 4243 auto FoundDecls = Importer.findDeclsInToCtx(DC, Name); 4244 for (auto *FoundDecl : FoundDecls) { 4245 if (!FoundDecl->isInIdentifierNamespace(IDNS)) 4246 continue; 4247 4248 if (auto *FoundVar = dyn_cast<VarDecl>(FoundDecl)) { 4249 if (!hasSameVisibilityContextAndLinkage(FoundVar, D)) 4250 continue; 4251 if (Importer.IsStructurallyEquivalent(D->getType(), 4252 FoundVar->getType())) { 4253 4254 // The VarDecl in the "From" context has a definition, but in the 4255 // "To" context we already have a definition. 4256 VarDecl *FoundDef = FoundVar->getDefinition(); 4257 if (D->isThisDeclarationADefinition() && FoundDef) 4258 // FIXME Check for ODR error if the two definitions have 4259 // different initializers? 4260 return Importer.MapImported(D, FoundDef); 4261 4262 // The VarDecl in the "From" context has an initializer, but in the 4263 // "To" context we already have an initializer. 4264 const VarDecl *FoundDInit = nullptr; 4265 if (D->getInit() && FoundVar->getAnyInitializer(FoundDInit)) 4266 // FIXME Diagnose ODR error if the two initializers are different? 4267 return Importer.MapImported(D, const_cast<VarDecl*>(FoundDInit)); 4268 4269 FoundByLookup = FoundVar; 4270 break; 4271 } 4272 4273 const ArrayType *FoundArray 4274 = Importer.getToContext().getAsArrayType(FoundVar->getType()); 4275 const ArrayType *TArray 4276 = Importer.getToContext().getAsArrayType(D->getType()); 4277 if (FoundArray && TArray) { 4278 if (isa<IncompleteArrayType>(FoundArray) && 4279 isa<ConstantArrayType>(TArray)) { 4280 // Import the type. 4281 if (auto TyOrErr = import(D->getType())) 4282 FoundVar->setType(*TyOrErr); 4283 else 4284 return TyOrErr.takeError(); 4285 4286 FoundByLookup = FoundVar; 4287 break; 4288 } else if (isa<IncompleteArrayType>(TArray) && 4289 isa<ConstantArrayType>(FoundArray)) { 4290 FoundByLookup = FoundVar; 4291 break; 4292 } 4293 } 4294 4295 Importer.ToDiag(Loc, diag::warn_odr_variable_type_inconsistent) 4296 << Name << D->getType() << FoundVar->getType(); 4297 Importer.ToDiag(FoundVar->getLocation(), diag::note_odr_value_here) 4298 << FoundVar->getType(); 4299 ConflictingDecls.push_back(FoundDecl); 4300 } 4301 } 4302 4303 if (!ConflictingDecls.empty()) { 4304 ExpectedName NameOrErr = Importer.HandleNameConflict( 4305 Name, DC, IDNS, ConflictingDecls.data(), ConflictingDecls.size()); 4306 if (NameOrErr) 4307 Name = NameOrErr.get(); 4308 else 4309 return NameOrErr.takeError(); 4310 } 4311 } 4312 4313 Error Err = Error::success(); 4314 auto ToType = importChecked(Err, D->getType()); 4315 auto ToTypeSourceInfo = importChecked(Err, D->getTypeSourceInfo()); 4316 auto ToInnerLocStart = importChecked(Err, D->getInnerLocStart()); 4317 auto ToQualifierLoc = importChecked(Err, D->getQualifierLoc()); 4318 if (Err) 4319 return std::move(Err); 4320 4321 VarDecl *ToVar; 4322 if (auto *FromDecomp = dyn_cast<DecompositionDecl>(D)) { 4323 SmallVector<BindingDecl *> Bindings(FromDecomp->bindings().size()); 4324 if (Error Err = 4325 ImportArrayChecked(FromDecomp->bindings(), Bindings.begin())) 4326 return std::move(Err); 4327 DecompositionDecl *ToDecomp; 4328 if (GetImportedOrCreateDecl( 4329 ToDecomp, FromDecomp, Importer.getToContext(), DC, ToInnerLocStart, 4330 Loc, ToType, ToTypeSourceInfo, D->getStorageClass(), Bindings)) 4331 return ToDecomp; 4332 ToVar = ToDecomp; 4333 } else { 4334 // Create the imported variable. 4335 if (GetImportedOrCreateDecl(ToVar, D, Importer.getToContext(), DC, 4336 ToInnerLocStart, Loc, 4337 Name.getAsIdentifierInfo(), ToType, 4338 ToTypeSourceInfo, D->getStorageClass())) 4339 return ToVar; 4340 } 4341 4342 ToVar->setTSCSpec(D->getTSCSpec()); 4343 ToVar->setQualifierInfo(ToQualifierLoc); 4344 ToVar->setAccess(D->getAccess()); 4345 ToVar->setLexicalDeclContext(LexicalDC); 4346 4347 if (FoundByLookup) { 4348 auto *Recent = const_cast<VarDecl *>(FoundByLookup->getMostRecentDecl()); 4349 ToVar->setPreviousDecl(Recent); 4350 } 4351 4352 // Import the described template, if any. 4353 if (D->getDescribedVarTemplate()) { 4354 auto ToVTOrErr = import(D->getDescribedVarTemplate()); 4355 if (!ToVTOrErr) 4356 return ToVTOrErr.takeError(); 4357 } 4358 4359 if (Error Err = ImportInitializer(D, ToVar)) 4360 return std::move(Err); 4361 4362 if (D->isConstexpr()) 4363 ToVar->setConstexpr(true); 4364 4365 addDeclToContexts(D, ToVar); 4366 4367 // Import the rest of the chain. I.e. import all subsequent declarations. 4368 for (++RedeclIt; RedeclIt != Redecls.end(); ++RedeclIt) { 4369 ExpectedDecl RedeclOrErr = import(*RedeclIt); 4370 if (!RedeclOrErr) 4371 return RedeclOrErr.takeError(); 4372 } 4373 4374 return ToVar; 4375 } 4376 4377 ExpectedDecl ASTNodeImporter::VisitImplicitParamDecl(ImplicitParamDecl *D) { 4378 // Parameters are created in the translation unit's context, then moved 4379 // into the function declaration's context afterward. 4380 DeclContext *DC = Importer.getToContext().getTranslationUnitDecl(); 4381 4382 Error Err = Error::success(); 4383 auto ToDeclName = importChecked(Err, D->getDeclName()); 4384 auto ToLocation = importChecked(Err, D->getLocation()); 4385 auto ToType = importChecked(Err, D->getType()); 4386 if (Err) 4387 return std::move(Err); 4388 4389 // Create the imported parameter. 4390 ImplicitParamDecl *ToParm = nullptr; 4391 if (GetImportedOrCreateDecl(ToParm, D, Importer.getToContext(), DC, 4392 ToLocation, ToDeclName.getAsIdentifierInfo(), 4393 ToType, D->getParameterKind())) 4394 return ToParm; 4395 return ToParm; 4396 } 4397 4398 Error ASTNodeImporter::ImportDefaultArgOfParmVarDecl( 4399 const ParmVarDecl *FromParam, ParmVarDecl *ToParam) { 4400 ToParam->setHasInheritedDefaultArg(FromParam->hasInheritedDefaultArg()); 4401 ToParam->setKNRPromoted(FromParam->isKNRPromoted()); 4402 4403 if (FromParam->hasUninstantiatedDefaultArg()) { 4404 if (auto ToDefArgOrErr = import(FromParam->getUninstantiatedDefaultArg())) 4405 ToParam->setUninstantiatedDefaultArg(*ToDefArgOrErr); 4406 else 4407 return ToDefArgOrErr.takeError(); 4408 } else if (FromParam->hasUnparsedDefaultArg()) { 4409 ToParam->setUnparsedDefaultArg(); 4410 } else if (FromParam->hasDefaultArg()) { 4411 if (auto ToDefArgOrErr = import(FromParam->getDefaultArg())) 4412 ToParam->setDefaultArg(*ToDefArgOrErr); 4413 else 4414 return ToDefArgOrErr.takeError(); 4415 } 4416 4417 return Error::success(); 4418 } 4419 4420 Expected<InheritedConstructor> 4421 ASTNodeImporter::ImportInheritedConstructor(const InheritedConstructor &From) { 4422 Error Err = Error::success(); 4423 CXXConstructorDecl *ToBaseCtor = importChecked(Err, From.getConstructor()); 4424 ConstructorUsingShadowDecl *ToShadow = 4425 importChecked(Err, From.getShadowDecl()); 4426 if (Err) 4427 return std::move(Err); 4428 return InheritedConstructor(ToShadow, ToBaseCtor); 4429 } 4430 4431 ExpectedDecl ASTNodeImporter::VisitParmVarDecl(ParmVarDecl *D) { 4432 // Parameters are created in the translation unit's context, then moved 4433 // into the function declaration's context afterward. 4434 DeclContext *DC = Importer.getToContext().getTranslationUnitDecl(); 4435 4436 Error Err = Error::success(); 4437 auto ToDeclName = importChecked(Err, D->getDeclName()); 4438 auto ToLocation = importChecked(Err, D->getLocation()); 4439 auto ToInnerLocStart = importChecked(Err, D->getInnerLocStart()); 4440 auto ToType = importChecked(Err, D->getType()); 4441 auto ToTypeSourceInfo = importChecked(Err, D->getTypeSourceInfo()); 4442 if (Err) 4443 return std::move(Err); 4444 4445 ParmVarDecl *ToParm; 4446 if (GetImportedOrCreateDecl(ToParm, D, Importer.getToContext(), DC, 4447 ToInnerLocStart, ToLocation, 4448 ToDeclName.getAsIdentifierInfo(), ToType, 4449 ToTypeSourceInfo, D->getStorageClass(), 4450 /*DefaultArg*/ nullptr)) 4451 return ToParm; 4452 4453 // Set the default argument. It should be no problem if it was already done. 4454 // Do not import the default expression before GetImportedOrCreateDecl call 4455 // to avoid possible infinite import loop because circular dependency. 4456 if (Error Err = ImportDefaultArgOfParmVarDecl(D, ToParm)) 4457 return std::move(Err); 4458 4459 if (D->isObjCMethodParameter()) { 4460 ToParm->setObjCMethodScopeInfo(D->getFunctionScopeIndex()); 4461 ToParm->setObjCDeclQualifier(D->getObjCDeclQualifier()); 4462 } else { 4463 ToParm->setScopeInfo(D->getFunctionScopeDepth(), 4464 D->getFunctionScopeIndex()); 4465 } 4466 4467 return ToParm; 4468 } 4469 4470 ExpectedDecl ASTNodeImporter::VisitObjCMethodDecl(ObjCMethodDecl *D) { 4471 // Import the major distinguishing characteristics of a method. 4472 DeclContext *DC, *LexicalDC; 4473 DeclarationName Name; 4474 SourceLocation Loc; 4475 NamedDecl *ToD; 4476 if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc)) 4477 return std::move(Err); 4478 if (ToD) 4479 return ToD; 4480 4481 auto FoundDecls = Importer.findDeclsInToCtx(DC, Name); 4482 for (auto *FoundDecl : FoundDecls) { 4483 if (auto *FoundMethod = dyn_cast<ObjCMethodDecl>(FoundDecl)) { 4484 if (FoundMethod->isInstanceMethod() != D->isInstanceMethod()) 4485 continue; 4486 4487 // Check return types. 4488 if (!Importer.IsStructurallyEquivalent(D->getReturnType(), 4489 FoundMethod->getReturnType())) { 4490 Importer.ToDiag(Loc, diag::warn_odr_objc_method_result_type_inconsistent) 4491 << D->isInstanceMethod() << Name << D->getReturnType() 4492 << FoundMethod->getReturnType(); 4493 Importer.ToDiag(FoundMethod->getLocation(), 4494 diag::note_odr_objc_method_here) 4495 << D->isInstanceMethod() << Name; 4496 4497 return make_error<ASTImportError>(ASTImportError::NameConflict); 4498 } 4499 4500 // Check the number of parameters. 4501 if (D->param_size() != FoundMethod->param_size()) { 4502 Importer.ToDiag(Loc, diag::warn_odr_objc_method_num_params_inconsistent) 4503 << D->isInstanceMethod() << Name 4504 << D->param_size() << FoundMethod->param_size(); 4505 Importer.ToDiag(FoundMethod->getLocation(), 4506 diag::note_odr_objc_method_here) 4507 << D->isInstanceMethod() << Name; 4508 4509 return make_error<ASTImportError>(ASTImportError::NameConflict); 4510 } 4511 4512 // Check parameter types. 4513 for (ObjCMethodDecl::param_iterator P = D->param_begin(), 4514 PEnd = D->param_end(), FoundP = FoundMethod->param_begin(); 4515 P != PEnd; ++P, ++FoundP) { 4516 if (!Importer.IsStructurallyEquivalent((*P)->getType(), 4517 (*FoundP)->getType())) { 4518 Importer.FromDiag((*P)->getLocation(), 4519 diag::warn_odr_objc_method_param_type_inconsistent) 4520 << D->isInstanceMethod() << Name 4521 << (*P)->getType() << (*FoundP)->getType(); 4522 Importer.ToDiag((*FoundP)->getLocation(), diag::note_odr_value_here) 4523 << (*FoundP)->getType(); 4524 4525 return make_error<ASTImportError>(ASTImportError::NameConflict); 4526 } 4527 } 4528 4529 // Check variadic/non-variadic. 4530 // Check the number of parameters. 4531 if (D->isVariadic() != FoundMethod->isVariadic()) { 4532 Importer.ToDiag(Loc, diag::warn_odr_objc_method_variadic_inconsistent) 4533 << D->isInstanceMethod() << Name; 4534 Importer.ToDiag(FoundMethod->getLocation(), 4535 diag::note_odr_objc_method_here) 4536 << D->isInstanceMethod() << Name; 4537 4538 return make_error<ASTImportError>(ASTImportError::NameConflict); 4539 } 4540 4541 // FIXME: Any other bits we need to merge? 4542 return Importer.MapImported(D, FoundMethod); 4543 } 4544 } 4545 4546 Error Err = Error::success(); 4547 auto ToEndLoc = importChecked(Err, D->getEndLoc()); 4548 auto ToReturnType = importChecked(Err, D->getReturnType()); 4549 auto ToReturnTypeSourceInfo = 4550 importChecked(Err, D->getReturnTypeSourceInfo()); 4551 if (Err) 4552 return std::move(Err); 4553 4554 ObjCMethodDecl *ToMethod; 4555 if (GetImportedOrCreateDecl( 4556 ToMethod, D, Importer.getToContext(), Loc, ToEndLoc, 4557 Name.getObjCSelector(), ToReturnType, ToReturnTypeSourceInfo, DC, 4558 D->isInstanceMethod(), D->isVariadic(), D->isPropertyAccessor(), 4559 D->isSynthesizedAccessorStub(), D->isImplicit(), D->isDefined(), 4560 D->getImplementationControl(), D->hasRelatedResultType())) 4561 return ToMethod; 4562 4563 // FIXME: When we decide to merge method definitions, we'll need to 4564 // deal with implicit parameters. 4565 4566 // Import the parameters 4567 SmallVector<ParmVarDecl *, 5> ToParams; 4568 for (auto *FromP : D->parameters()) { 4569 if (Expected<ParmVarDecl *> ToPOrErr = import(FromP)) 4570 ToParams.push_back(*ToPOrErr); 4571 else 4572 return ToPOrErr.takeError(); 4573 } 4574 4575 // Set the parameters. 4576 for (auto *ToParam : ToParams) { 4577 ToParam->setOwningFunction(ToMethod); 4578 ToMethod->addDeclInternal(ToParam); 4579 } 4580 4581 SmallVector<SourceLocation, 12> FromSelLocs; 4582 D->getSelectorLocs(FromSelLocs); 4583 SmallVector<SourceLocation, 12> ToSelLocs(FromSelLocs.size()); 4584 if (Error Err = ImportContainerChecked(FromSelLocs, ToSelLocs)) 4585 return std::move(Err); 4586 4587 ToMethod->setMethodParams(Importer.getToContext(), ToParams, ToSelLocs); 4588 4589 ToMethod->setLexicalDeclContext(LexicalDC); 4590 LexicalDC->addDeclInternal(ToMethod); 4591 4592 // Implicit params are declared when Sema encounters the definition but this 4593 // never happens when the method is imported. Manually declare the implicit 4594 // params now that the MethodDecl knows its class interface. 4595 if (D->getSelfDecl()) 4596 ToMethod->createImplicitParams(Importer.getToContext(), 4597 ToMethod->getClassInterface()); 4598 4599 return ToMethod; 4600 } 4601 4602 ExpectedDecl ASTNodeImporter::VisitObjCTypeParamDecl(ObjCTypeParamDecl *D) { 4603 // Import the major distinguishing characteristics of a category. 4604 DeclContext *DC, *LexicalDC; 4605 DeclarationName Name; 4606 SourceLocation Loc; 4607 NamedDecl *ToD; 4608 if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc)) 4609 return std::move(Err); 4610 if (ToD) 4611 return ToD; 4612 4613 Error Err = Error::success(); 4614 auto ToVarianceLoc = importChecked(Err, D->getVarianceLoc()); 4615 auto ToLocation = importChecked(Err, D->getLocation()); 4616 auto ToColonLoc = importChecked(Err, D->getColonLoc()); 4617 auto ToTypeSourceInfo = importChecked(Err, D->getTypeSourceInfo()); 4618 if (Err) 4619 return std::move(Err); 4620 4621 ObjCTypeParamDecl *Result; 4622 if (GetImportedOrCreateDecl( 4623 Result, D, Importer.getToContext(), DC, D->getVariance(), 4624 ToVarianceLoc, D->getIndex(), 4625 ToLocation, Name.getAsIdentifierInfo(), 4626 ToColonLoc, ToTypeSourceInfo)) 4627 return Result; 4628 4629 Result->setLexicalDeclContext(LexicalDC); 4630 return Result; 4631 } 4632 4633 ExpectedDecl ASTNodeImporter::VisitObjCCategoryDecl(ObjCCategoryDecl *D) { 4634 // Import the major distinguishing characteristics of a category. 4635 DeclContext *DC, *LexicalDC; 4636 DeclarationName Name; 4637 SourceLocation Loc; 4638 NamedDecl *ToD; 4639 if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc)) 4640 return std::move(Err); 4641 if (ToD) 4642 return ToD; 4643 4644 ObjCInterfaceDecl *ToInterface; 4645 if (Error Err = importInto(ToInterface, D->getClassInterface())) 4646 return std::move(Err); 4647 4648 // Determine if we've already encountered this category. 4649 ObjCCategoryDecl *MergeWithCategory 4650 = ToInterface->FindCategoryDeclaration(Name.getAsIdentifierInfo()); 4651 ObjCCategoryDecl *ToCategory = MergeWithCategory; 4652 if (!ToCategory) { 4653 4654 Error Err = Error::success(); 4655 auto ToAtStartLoc = importChecked(Err, D->getAtStartLoc()); 4656 auto ToCategoryNameLoc = importChecked(Err, D->getCategoryNameLoc()); 4657 auto ToIvarLBraceLoc = importChecked(Err, D->getIvarLBraceLoc()); 4658 auto ToIvarRBraceLoc = importChecked(Err, D->getIvarRBraceLoc()); 4659 if (Err) 4660 return std::move(Err); 4661 4662 if (GetImportedOrCreateDecl(ToCategory, D, Importer.getToContext(), DC, 4663 ToAtStartLoc, Loc, 4664 ToCategoryNameLoc, 4665 Name.getAsIdentifierInfo(), ToInterface, 4666 /*TypeParamList=*/nullptr, 4667 ToIvarLBraceLoc, 4668 ToIvarRBraceLoc)) 4669 return ToCategory; 4670 4671 ToCategory->setLexicalDeclContext(LexicalDC); 4672 LexicalDC->addDeclInternal(ToCategory); 4673 // Import the type parameter list after MapImported, to avoid 4674 // loops when bringing in their DeclContext. 4675 if (auto PListOrErr = ImportObjCTypeParamList(D->getTypeParamList())) 4676 ToCategory->setTypeParamList(*PListOrErr); 4677 else 4678 return PListOrErr.takeError(); 4679 4680 // Import protocols 4681 SmallVector<ObjCProtocolDecl *, 4> Protocols; 4682 SmallVector<SourceLocation, 4> ProtocolLocs; 4683 ObjCCategoryDecl::protocol_loc_iterator FromProtoLoc 4684 = D->protocol_loc_begin(); 4685 for (ObjCCategoryDecl::protocol_iterator FromProto = D->protocol_begin(), 4686 FromProtoEnd = D->protocol_end(); 4687 FromProto != FromProtoEnd; 4688 ++FromProto, ++FromProtoLoc) { 4689 if (Expected<ObjCProtocolDecl *> ToProtoOrErr = import(*FromProto)) 4690 Protocols.push_back(*ToProtoOrErr); 4691 else 4692 return ToProtoOrErr.takeError(); 4693 4694 if (ExpectedSLoc ToProtoLocOrErr = import(*FromProtoLoc)) 4695 ProtocolLocs.push_back(*ToProtoLocOrErr); 4696 else 4697 return ToProtoLocOrErr.takeError(); 4698 } 4699 4700 // FIXME: If we're merging, make sure that the protocol list is the same. 4701 ToCategory->setProtocolList(Protocols.data(), Protocols.size(), 4702 ProtocolLocs.data(), Importer.getToContext()); 4703 4704 } else { 4705 Importer.MapImported(D, ToCategory); 4706 } 4707 4708 // Import all of the members of this category. 4709 if (Error Err = ImportDeclContext(D)) 4710 return std::move(Err); 4711 4712 // If we have an implementation, import it as well. 4713 if (D->getImplementation()) { 4714 if (Expected<ObjCCategoryImplDecl *> ToImplOrErr = 4715 import(D->getImplementation())) 4716 ToCategory->setImplementation(*ToImplOrErr); 4717 else 4718 return ToImplOrErr.takeError(); 4719 } 4720 4721 return ToCategory; 4722 } 4723 4724 Error ASTNodeImporter::ImportDefinition( 4725 ObjCProtocolDecl *From, ObjCProtocolDecl *To, ImportDefinitionKind Kind) { 4726 if (To->getDefinition()) { 4727 if (shouldForceImportDeclContext(Kind)) 4728 if (Error Err = ImportDeclContext(From)) 4729 return Err; 4730 return Error::success(); 4731 } 4732 4733 // Start the protocol definition 4734 To->startDefinition(); 4735 4736 // Import protocols 4737 SmallVector<ObjCProtocolDecl *, 4> Protocols; 4738 SmallVector<SourceLocation, 4> ProtocolLocs; 4739 ObjCProtocolDecl::protocol_loc_iterator FromProtoLoc = 4740 From->protocol_loc_begin(); 4741 for (ObjCProtocolDecl::protocol_iterator FromProto = From->protocol_begin(), 4742 FromProtoEnd = From->protocol_end(); 4743 FromProto != FromProtoEnd; 4744 ++FromProto, ++FromProtoLoc) { 4745 if (Expected<ObjCProtocolDecl *> ToProtoOrErr = import(*FromProto)) 4746 Protocols.push_back(*ToProtoOrErr); 4747 else 4748 return ToProtoOrErr.takeError(); 4749 4750 if (ExpectedSLoc ToProtoLocOrErr = import(*FromProtoLoc)) 4751 ProtocolLocs.push_back(*ToProtoLocOrErr); 4752 else 4753 return ToProtoLocOrErr.takeError(); 4754 4755 } 4756 4757 // FIXME: If we're merging, make sure that the protocol list is the same. 4758 To->setProtocolList(Protocols.data(), Protocols.size(), 4759 ProtocolLocs.data(), Importer.getToContext()); 4760 4761 if (shouldForceImportDeclContext(Kind)) { 4762 // Import all of the members of this protocol. 4763 if (Error Err = ImportDeclContext(From, /*ForceImport=*/true)) 4764 return Err; 4765 } 4766 return Error::success(); 4767 } 4768 4769 ExpectedDecl ASTNodeImporter::VisitObjCProtocolDecl(ObjCProtocolDecl *D) { 4770 // If this protocol has a definition in the translation unit we're coming 4771 // from, but this particular declaration is not that definition, import the 4772 // definition and map to that. 4773 ObjCProtocolDecl *Definition = D->getDefinition(); 4774 if (Definition && Definition != D) { 4775 if (ExpectedDecl ImportedDefOrErr = import(Definition)) 4776 return Importer.MapImported(D, *ImportedDefOrErr); 4777 else 4778 return ImportedDefOrErr.takeError(); 4779 } 4780 4781 // Import the major distinguishing characteristics of a protocol. 4782 DeclContext *DC, *LexicalDC; 4783 DeclarationName Name; 4784 SourceLocation Loc; 4785 NamedDecl *ToD; 4786 if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc)) 4787 return std::move(Err); 4788 if (ToD) 4789 return ToD; 4790 4791 ObjCProtocolDecl *MergeWithProtocol = nullptr; 4792 auto FoundDecls = Importer.findDeclsInToCtx(DC, Name); 4793 for (auto *FoundDecl : FoundDecls) { 4794 if (!FoundDecl->isInIdentifierNamespace(Decl::IDNS_ObjCProtocol)) 4795 continue; 4796 4797 if ((MergeWithProtocol = dyn_cast<ObjCProtocolDecl>(FoundDecl))) 4798 break; 4799 } 4800 4801 ObjCProtocolDecl *ToProto = MergeWithProtocol; 4802 if (!ToProto) { 4803 auto ToAtBeginLocOrErr = import(D->getAtStartLoc()); 4804 if (!ToAtBeginLocOrErr) 4805 return ToAtBeginLocOrErr.takeError(); 4806 4807 if (GetImportedOrCreateDecl(ToProto, D, Importer.getToContext(), DC, 4808 Name.getAsIdentifierInfo(), Loc, 4809 *ToAtBeginLocOrErr, 4810 /*PrevDecl=*/nullptr)) 4811 return ToProto; 4812 ToProto->setLexicalDeclContext(LexicalDC); 4813 LexicalDC->addDeclInternal(ToProto); 4814 } 4815 4816 Importer.MapImported(D, ToProto); 4817 4818 if (D->isThisDeclarationADefinition()) 4819 if (Error Err = ImportDefinition(D, ToProto)) 4820 return std::move(Err); 4821 4822 return ToProto; 4823 } 4824 4825 ExpectedDecl ASTNodeImporter::VisitLinkageSpecDecl(LinkageSpecDecl *D) { 4826 DeclContext *DC, *LexicalDC; 4827 if (Error Err = ImportDeclContext(D, DC, LexicalDC)) 4828 return std::move(Err); 4829 4830 ExpectedSLoc ExternLocOrErr = import(D->getExternLoc()); 4831 if (!ExternLocOrErr) 4832 return ExternLocOrErr.takeError(); 4833 4834 ExpectedSLoc LangLocOrErr = import(D->getLocation()); 4835 if (!LangLocOrErr) 4836 return LangLocOrErr.takeError(); 4837 4838 bool HasBraces = D->hasBraces(); 4839 4840 LinkageSpecDecl *ToLinkageSpec; 4841 if (GetImportedOrCreateDecl(ToLinkageSpec, D, Importer.getToContext(), DC, 4842 *ExternLocOrErr, *LangLocOrErr, 4843 D->getLanguage(), HasBraces)) 4844 return ToLinkageSpec; 4845 4846 if (HasBraces) { 4847 ExpectedSLoc RBraceLocOrErr = import(D->getRBraceLoc()); 4848 if (!RBraceLocOrErr) 4849 return RBraceLocOrErr.takeError(); 4850 ToLinkageSpec->setRBraceLoc(*RBraceLocOrErr); 4851 } 4852 4853 ToLinkageSpec->setLexicalDeclContext(LexicalDC); 4854 LexicalDC->addDeclInternal(ToLinkageSpec); 4855 4856 return ToLinkageSpec; 4857 } 4858 4859 ExpectedDecl ASTNodeImporter::ImportUsingShadowDecls(BaseUsingDecl *D, 4860 BaseUsingDecl *ToSI) { 4861 for (UsingShadowDecl *FromShadow : D->shadows()) { 4862 if (Expected<UsingShadowDecl *> ToShadowOrErr = import(FromShadow)) 4863 ToSI->addShadowDecl(*ToShadowOrErr); 4864 else 4865 // FIXME: We return error here but the definition is already created 4866 // and available with lookups. How to fix this?.. 4867 return ToShadowOrErr.takeError(); 4868 } 4869 return ToSI; 4870 } 4871 4872 ExpectedDecl ASTNodeImporter::VisitUsingDecl(UsingDecl *D) { 4873 DeclContext *DC, *LexicalDC; 4874 DeclarationName Name; 4875 SourceLocation Loc; 4876 NamedDecl *ToD = nullptr; 4877 if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc)) 4878 return std::move(Err); 4879 if (ToD) 4880 return ToD; 4881 4882 Error Err = Error::success(); 4883 auto ToLoc = importChecked(Err, D->getNameInfo().getLoc()); 4884 auto ToUsingLoc = importChecked(Err, D->getUsingLoc()); 4885 auto ToQualifierLoc = importChecked(Err, D->getQualifierLoc()); 4886 if (Err) 4887 return std::move(Err); 4888 4889 DeclarationNameInfo NameInfo(Name, ToLoc); 4890 if (Error Err = ImportDeclarationNameLoc(D->getNameInfo(), NameInfo)) 4891 return std::move(Err); 4892 4893 UsingDecl *ToUsing; 4894 if (GetImportedOrCreateDecl(ToUsing, D, Importer.getToContext(), DC, 4895 ToUsingLoc, ToQualifierLoc, NameInfo, 4896 D->hasTypename())) 4897 return ToUsing; 4898 4899 ToUsing->setLexicalDeclContext(LexicalDC); 4900 LexicalDC->addDeclInternal(ToUsing); 4901 4902 if (NamedDecl *FromPattern = 4903 Importer.getFromContext().getInstantiatedFromUsingDecl(D)) { 4904 if (Expected<NamedDecl *> ToPatternOrErr = import(FromPattern)) 4905 Importer.getToContext().setInstantiatedFromUsingDecl( 4906 ToUsing, *ToPatternOrErr); 4907 else 4908 return ToPatternOrErr.takeError(); 4909 } 4910 4911 return ImportUsingShadowDecls(D, ToUsing); 4912 } 4913 4914 ExpectedDecl ASTNodeImporter::VisitUsingEnumDecl(UsingEnumDecl *D) { 4915 DeclContext *DC, *LexicalDC; 4916 DeclarationName Name; 4917 SourceLocation Loc; 4918 NamedDecl *ToD = nullptr; 4919 if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc)) 4920 return std::move(Err); 4921 if (ToD) 4922 return ToD; 4923 4924 Error Err = Error::success(); 4925 auto ToUsingLoc = importChecked(Err, D->getUsingLoc()); 4926 auto ToEnumLoc = importChecked(Err, D->getEnumLoc()); 4927 auto ToNameLoc = importChecked(Err, D->getLocation()); 4928 auto *ToEnumType = importChecked(Err, D->getEnumType()); 4929 if (Err) 4930 return std::move(Err); 4931 4932 UsingEnumDecl *ToUsingEnum; 4933 if (GetImportedOrCreateDecl(ToUsingEnum, D, Importer.getToContext(), DC, 4934 ToUsingLoc, ToEnumLoc, ToNameLoc, ToEnumType)) 4935 return ToUsingEnum; 4936 4937 ToUsingEnum->setLexicalDeclContext(LexicalDC); 4938 LexicalDC->addDeclInternal(ToUsingEnum); 4939 4940 if (UsingEnumDecl *FromPattern = 4941 Importer.getFromContext().getInstantiatedFromUsingEnumDecl(D)) { 4942 if (Expected<UsingEnumDecl *> ToPatternOrErr = import(FromPattern)) 4943 Importer.getToContext().setInstantiatedFromUsingEnumDecl(ToUsingEnum, 4944 *ToPatternOrErr); 4945 else 4946 return ToPatternOrErr.takeError(); 4947 } 4948 4949 return ImportUsingShadowDecls(D, ToUsingEnum); 4950 } 4951 4952 ExpectedDecl ASTNodeImporter::VisitUsingShadowDecl(UsingShadowDecl *D) { 4953 DeclContext *DC, *LexicalDC; 4954 DeclarationName Name; 4955 SourceLocation Loc; 4956 NamedDecl *ToD = nullptr; 4957 if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc)) 4958 return std::move(Err); 4959 if (ToD) 4960 return ToD; 4961 4962 Expected<BaseUsingDecl *> ToIntroducerOrErr = import(D->getIntroducer()); 4963 if (!ToIntroducerOrErr) 4964 return ToIntroducerOrErr.takeError(); 4965 4966 Expected<NamedDecl *> ToTargetOrErr = import(D->getTargetDecl()); 4967 if (!ToTargetOrErr) 4968 return ToTargetOrErr.takeError(); 4969 4970 UsingShadowDecl *ToShadow; 4971 if (auto *FromConstructorUsingShadow = 4972 dyn_cast<ConstructorUsingShadowDecl>(D)) { 4973 Error Err = Error::success(); 4974 ConstructorUsingShadowDecl *Nominated = importChecked( 4975 Err, FromConstructorUsingShadow->getNominatedBaseClassShadowDecl()); 4976 if (Err) 4977 return std::move(Err); 4978 // The 'Target' parameter of ConstructorUsingShadowDecl constructor 4979 // is really the "NominatedBaseClassShadowDecl" value if it exists 4980 // (see code of ConstructorUsingShadowDecl::ConstructorUsingShadowDecl). 4981 // We should pass the NominatedBaseClassShadowDecl to it (if non-null) to 4982 // get the correct values. 4983 if (GetImportedOrCreateDecl<ConstructorUsingShadowDecl>( 4984 ToShadow, D, Importer.getToContext(), DC, Loc, 4985 cast<UsingDecl>(*ToIntroducerOrErr), 4986 Nominated ? Nominated : *ToTargetOrErr, 4987 FromConstructorUsingShadow->constructsVirtualBase())) 4988 return ToShadow; 4989 } else { 4990 if (GetImportedOrCreateDecl(ToShadow, D, Importer.getToContext(), DC, Loc, 4991 Name, *ToIntroducerOrErr, *ToTargetOrErr)) 4992 return ToShadow; 4993 } 4994 4995 ToShadow->setLexicalDeclContext(LexicalDC); 4996 ToShadow->setAccess(D->getAccess()); 4997 4998 if (UsingShadowDecl *FromPattern = 4999 Importer.getFromContext().getInstantiatedFromUsingShadowDecl(D)) { 5000 if (Expected<UsingShadowDecl *> ToPatternOrErr = import(FromPattern)) 5001 Importer.getToContext().setInstantiatedFromUsingShadowDecl( 5002 ToShadow, *ToPatternOrErr); 5003 else 5004 // FIXME: We return error here but the definition is already created 5005 // and available with lookups. How to fix this?.. 5006 return ToPatternOrErr.takeError(); 5007 } 5008 5009 LexicalDC->addDeclInternal(ToShadow); 5010 5011 return ToShadow; 5012 } 5013 5014 ExpectedDecl ASTNodeImporter::VisitUsingDirectiveDecl(UsingDirectiveDecl *D) { 5015 DeclContext *DC, *LexicalDC; 5016 DeclarationName Name; 5017 SourceLocation Loc; 5018 NamedDecl *ToD = nullptr; 5019 if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc)) 5020 return std::move(Err); 5021 if (ToD) 5022 return ToD; 5023 5024 auto ToComAncestorOrErr = Importer.ImportContext(D->getCommonAncestor()); 5025 if (!ToComAncestorOrErr) 5026 return ToComAncestorOrErr.takeError(); 5027 5028 Error Err = Error::success(); 5029 auto ToNominatedNamespace = importChecked(Err, D->getNominatedNamespace()); 5030 auto ToUsingLoc = importChecked(Err, D->getUsingLoc()); 5031 auto ToNamespaceKeyLocation = 5032 importChecked(Err, D->getNamespaceKeyLocation()); 5033 auto ToQualifierLoc = importChecked(Err, D->getQualifierLoc()); 5034 auto ToIdentLocation = importChecked(Err, D->getIdentLocation()); 5035 if (Err) 5036 return std::move(Err); 5037 5038 UsingDirectiveDecl *ToUsingDir; 5039 if (GetImportedOrCreateDecl(ToUsingDir, D, Importer.getToContext(), DC, 5040 ToUsingLoc, 5041 ToNamespaceKeyLocation, 5042 ToQualifierLoc, 5043 ToIdentLocation, 5044 ToNominatedNamespace, *ToComAncestorOrErr)) 5045 return ToUsingDir; 5046 5047 ToUsingDir->setLexicalDeclContext(LexicalDC); 5048 LexicalDC->addDeclInternal(ToUsingDir); 5049 5050 return ToUsingDir; 5051 } 5052 5053 ExpectedDecl ASTNodeImporter::VisitUsingPackDecl(UsingPackDecl *D) { 5054 DeclContext *DC, *LexicalDC; 5055 DeclarationName Name; 5056 SourceLocation Loc; 5057 NamedDecl *ToD = nullptr; 5058 if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc)) 5059 return std::move(Err); 5060 if (ToD) 5061 return ToD; 5062 5063 auto ToInstantiatedFromUsingOrErr = 5064 Importer.Import(D->getInstantiatedFromUsingDecl()); 5065 if (!ToInstantiatedFromUsingOrErr) 5066 return ToInstantiatedFromUsingOrErr.takeError(); 5067 SmallVector<NamedDecl *, 4> Expansions(D->expansions().size()); 5068 if (Error Err = ImportArrayChecked(D->expansions(), Expansions.begin())) 5069 return std::move(Err); 5070 5071 UsingPackDecl *ToUsingPack; 5072 if (GetImportedOrCreateDecl(ToUsingPack, D, Importer.getToContext(), DC, 5073 cast<NamedDecl>(*ToInstantiatedFromUsingOrErr), 5074 Expansions)) 5075 return ToUsingPack; 5076 5077 addDeclToContexts(D, ToUsingPack); 5078 5079 return ToUsingPack; 5080 } 5081 5082 ExpectedDecl ASTNodeImporter::VisitUnresolvedUsingValueDecl( 5083 UnresolvedUsingValueDecl *D) { 5084 DeclContext *DC, *LexicalDC; 5085 DeclarationName Name; 5086 SourceLocation Loc; 5087 NamedDecl *ToD = nullptr; 5088 if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc)) 5089 return std::move(Err); 5090 if (ToD) 5091 return ToD; 5092 5093 Error Err = Error::success(); 5094 auto ToLoc = importChecked(Err, D->getNameInfo().getLoc()); 5095 auto ToUsingLoc = importChecked(Err, D->getUsingLoc()); 5096 auto ToQualifierLoc = importChecked(Err, D->getQualifierLoc()); 5097 auto ToEllipsisLoc = importChecked(Err, D->getEllipsisLoc()); 5098 if (Err) 5099 return std::move(Err); 5100 5101 DeclarationNameInfo NameInfo(Name, ToLoc); 5102 if (Error Err = ImportDeclarationNameLoc(D->getNameInfo(), NameInfo)) 5103 return std::move(Err); 5104 5105 UnresolvedUsingValueDecl *ToUsingValue; 5106 if (GetImportedOrCreateDecl(ToUsingValue, D, Importer.getToContext(), DC, 5107 ToUsingLoc, ToQualifierLoc, NameInfo, 5108 ToEllipsisLoc)) 5109 return ToUsingValue; 5110 5111 ToUsingValue->setAccess(D->getAccess()); 5112 ToUsingValue->setLexicalDeclContext(LexicalDC); 5113 LexicalDC->addDeclInternal(ToUsingValue); 5114 5115 return ToUsingValue; 5116 } 5117 5118 ExpectedDecl ASTNodeImporter::VisitUnresolvedUsingTypenameDecl( 5119 UnresolvedUsingTypenameDecl *D) { 5120 DeclContext *DC, *LexicalDC; 5121 DeclarationName Name; 5122 SourceLocation Loc; 5123 NamedDecl *ToD = nullptr; 5124 if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc)) 5125 return std::move(Err); 5126 if (ToD) 5127 return ToD; 5128 5129 Error Err = Error::success(); 5130 auto ToUsingLoc = importChecked(Err, D->getUsingLoc()); 5131 auto ToTypenameLoc = importChecked(Err, D->getTypenameLoc()); 5132 auto ToQualifierLoc = importChecked(Err, D->getQualifierLoc()); 5133 auto ToEllipsisLoc = importChecked(Err, D->getEllipsisLoc()); 5134 if (Err) 5135 return std::move(Err); 5136 5137 UnresolvedUsingTypenameDecl *ToUsing; 5138 if (GetImportedOrCreateDecl(ToUsing, D, Importer.getToContext(), DC, 5139 ToUsingLoc, ToTypenameLoc, 5140 ToQualifierLoc, Loc, Name, ToEllipsisLoc)) 5141 return ToUsing; 5142 5143 ToUsing->setAccess(D->getAccess()); 5144 ToUsing->setLexicalDeclContext(LexicalDC); 5145 LexicalDC->addDeclInternal(ToUsing); 5146 5147 return ToUsing; 5148 } 5149 5150 ExpectedDecl ASTNodeImporter::VisitBuiltinTemplateDecl(BuiltinTemplateDecl *D) { 5151 Decl* ToD = nullptr; 5152 switch (D->getBuiltinTemplateKind()) { 5153 case BuiltinTemplateKind::BTK__make_integer_seq: 5154 ToD = Importer.getToContext().getMakeIntegerSeqDecl(); 5155 break; 5156 case BuiltinTemplateKind::BTK__type_pack_element: 5157 ToD = Importer.getToContext().getTypePackElementDecl(); 5158 break; 5159 } 5160 assert(ToD && "BuiltinTemplateDecl of unsupported kind!"); 5161 Importer.MapImported(D, ToD); 5162 return ToD; 5163 } 5164 5165 Error ASTNodeImporter::ImportDefinition( 5166 ObjCInterfaceDecl *From, ObjCInterfaceDecl *To, ImportDefinitionKind Kind) { 5167 if (To->getDefinition()) { 5168 // Check consistency of superclass. 5169 ObjCInterfaceDecl *FromSuper = From->getSuperClass(); 5170 if (FromSuper) { 5171 if (auto FromSuperOrErr = import(FromSuper)) 5172 FromSuper = *FromSuperOrErr; 5173 else 5174 return FromSuperOrErr.takeError(); 5175 } 5176 5177 ObjCInterfaceDecl *ToSuper = To->getSuperClass(); 5178 if ((bool)FromSuper != (bool)ToSuper || 5179 (FromSuper && !declaresSameEntity(FromSuper, ToSuper))) { 5180 Importer.ToDiag(To->getLocation(), 5181 diag::warn_odr_objc_superclass_inconsistent) 5182 << To->getDeclName(); 5183 if (ToSuper) 5184 Importer.ToDiag(To->getSuperClassLoc(), diag::note_odr_objc_superclass) 5185 << To->getSuperClass()->getDeclName(); 5186 else 5187 Importer.ToDiag(To->getLocation(), 5188 diag::note_odr_objc_missing_superclass); 5189 if (From->getSuperClass()) 5190 Importer.FromDiag(From->getSuperClassLoc(), 5191 diag::note_odr_objc_superclass) 5192 << From->getSuperClass()->getDeclName(); 5193 else 5194 Importer.FromDiag(From->getLocation(), 5195 diag::note_odr_objc_missing_superclass); 5196 } 5197 5198 if (shouldForceImportDeclContext(Kind)) 5199 if (Error Err = ImportDeclContext(From)) 5200 return Err; 5201 return Error::success(); 5202 } 5203 5204 // Start the definition. 5205 To->startDefinition(); 5206 5207 // If this class has a superclass, import it. 5208 if (From->getSuperClass()) { 5209 if (auto SuperTInfoOrErr = import(From->getSuperClassTInfo())) 5210 To->setSuperClass(*SuperTInfoOrErr); 5211 else 5212 return SuperTInfoOrErr.takeError(); 5213 } 5214 5215 // Import protocols 5216 SmallVector<ObjCProtocolDecl *, 4> Protocols; 5217 SmallVector<SourceLocation, 4> ProtocolLocs; 5218 ObjCInterfaceDecl::protocol_loc_iterator FromProtoLoc = 5219 From->protocol_loc_begin(); 5220 5221 for (ObjCInterfaceDecl::protocol_iterator FromProto = From->protocol_begin(), 5222 FromProtoEnd = From->protocol_end(); 5223 FromProto != FromProtoEnd; 5224 ++FromProto, ++FromProtoLoc) { 5225 if (Expected<ObjCProtocolDecl *> ToProtoOrErr = import(*FromProto)) 5226 Protocols.push_back(*ToProtoOrErr); 5227 else 5228 return ToProtoOrErr.takeError(); 5229 5230 if (ExpectedSLoc ToProtoLocOrErr = import(*FromProtoLoc)) 5231 ProtocolLocs.push_back(*ToProtoLocOrErr); 5232 else 5233 return ToProtoLocOrErr.takeError(); 5234 5235 } 5236 5237 // FIXME: If we're merging, make sure that the protocol list is the same. 5238 To->setProtocolList(Protocols.data(), Protocols.size(), 5239 ProtocolLocs.data(), Importer.getToContext()); 5240 5241 // Import categories. When the categories themselves are imported, they'll 5242 // hook themselves into this interface. 5243 for (auto *Cat : From->known_categories()) { 5244 auto ToCatOrErr = import(Cat); 5245 if (!ToCatOrErr) 5246 return ToCatOrErr.takeError(); 5247 } 5248 5249 // If we have an @implementation, import it as well. 5250 if (From->getImplementation()) { 5251 if (Expected<ObjCImplementationDecl *> ToImplOrErr = 5252 import(From->getImplementation())) 5253 To->setImplementation(*ToImplOrErr); 5254 else 5255 return ToImplOrErr.takeError(); 5256 } 5257 5258 // Import all of the members of this class. 5259 if (Error Err = ImportDeclContext(From, /*ForceImport=*/true)) 5260 return Err; 5261 5262 return Error::success(); 5263 } 5264 5265 Expected<ObjCTypeParamList *> 5266 ASTNodeImporter::ImportObjCTypeParamList(ObjCTypeParamList *list) { 5267 if (!list) 5268 return nullptr; 5269 5270 SmallVector<ObjCTypeParamDecl *, 4> toTypeParams; 5271 for (auto *fromTypeParam : *list) { 5272 if (auto toTypeParamOrErr = import(fromTypeParam)) 5273 toTypeParams.push_back(*toTypeParamOrErr); 5274 else 5275 return toTypeParamOrErr.takeError(); 5276 } 5277 5278 auto LAngleLocOrErr = import(list->getLAngleLoc()); 5279 if (!LAngleLocOrErr) 5280 return LAngleLocOrErr.takeError(); 5281 5282 auto RAngleLocOrErr = import(list->getRAngleLoc()); 5283 if (!RAngleLocOrErr) 5284 return RAngleLocOrErr.takeError(); 5285 5286 return ObjCTypeParamList::create(Importer.getToContext(), 5287 *LAngleLocOrErr, 5288 toTypeParams, 5289 *RAngleLocOrErr); 5290 } 5291 5292 ExpectedDecl ASTNodeImporter::VisitObjCInterfaceDecl(ObjCInterfaceDecl *D) { 5293 // If this class has a definition in the translation unit we're coming from, 5294 // but this particular declaration is not that definition, import the 5295 // definition and map to that. 5296 ObjCInterfaceDecl *Definition = D->getDefinition(); 5297 if (Definition && Definition != D) { 5298 if (ExpectedDecl ImportedDefOrErr = import(Definition)) 5299 return Importer.MapImported(D, *ImportedDefOrErr); 5300 else 5301 return ImportedDefOrErr.takeError(); 5302 } 5303 5304 // Import the major distinguishing characteristics of an @interface. 5305 DeclContext *DC, *LexicalDC; 5306 DeclarationName Name; 5307 SourceLocation Loc; 5308 NamedDecl *ToD; 5309 if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc)) 5310 return std::move(Err); 5311 if (ToD) 5312 return ToD; 5313 5314 // Look for an existing interface with the same name. 5315 ObjCInterfaceDecl *MergeWithIface = nullptr; 5316 auto FoundDecls = Importer.findDeclsInToCtx(DC, Name); 5317 for (auto *FoundDecl : FoundDecls) { 5318 if (!FoundDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary)) 5319 continue; 5320 5321 if ((MergeWithIface = dyn_cast<ObjCInterfaceDecl>(FoundDecl))) 5322 break; 5323 } 5324 5325 // Create an interface declaration, if one does not already exist. 5326 ObjCInterfaceDecl *ToIface = MergeWithIface; 5327 if (!ToIface) { 5328 ExpectedSLoc AtBeginLocOrErr = import(D->getAtStartLoc()); 5329 if (!AtBeginLocOrErr) 5330 return AtBeginLocOrErr.takeError(); 5331 5332 if (GetImportedOrCreateDecl( 5333 ToIface, D, Importer.getToContext(), DC, 5334 *AtBeginLocOrErr, Name.getAsIdentifierInfo(), 5335 /*TypeParamList=*/nullptr, 5336 /*PrevDecl=*/nullptr, Loc, D->isImplicitInterfaceDecl())) 5337 return ToIface; 5338 ToIface->setLexicalDeclContext(LexicalDC); 5339 LexicalDC->addDeclInternal(ToIface); 5340 } 5341 Importer.MapImported(D, ToIface); 5342 // Import the type parameter list after MapImported, to avoid 5343 // loops when bringing in their DeclContext. 5344 if (auto ToPListOrErr = 5345 ImportObjCTypeParamList(D->getTypeParamListAsWritten())) 5346 ToIface->setTypeParamList(*ToPListOrErr); 5347 else 5348 return ToPListOrErr.takeError(); 5349 5350 if (D->isThisDeclarationADefinition()) 5351 if (Error Err = ImportDefinition(D, ToIface)) 5352 return std::move(Err); 5353 5354 return ToIface; 5355 } 5356 5357 ExpectedDecl 5358 ASTNodeImporter::VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D) { 5359 ObjCCategoryDecl *Category; 5360 if (Error Err = importInto(Category, D->getCategoryDecl())) 5361 return std::move(Err); 5362 5363 ObjCCategoryImplDecl *ToImpl = Category->getImplementation(); 5364 if (!ToImpl) { 5365 DeclContext *DC, *LexicalDC; 5366 if (Error Err = ImportDeclContext(D, DC, LexicalDC)) 5367 return std::move(Err); 5368 5369 Error Err = Error::success(); 5370 auto ToLocation = importChecked(Err, D->getLocation()); 5371 auto ToAtStartLoc = importChecked(Err, D->getAtStartLoc()); 5372 auto ToCategoryNameLoc = importChecked(Err, D->getCategoryNameLoc()); 5373 if (Err) 5374 return std::move(Err); 5375 5376 if (GetImportedOrCreateDecl( 5377 ToImpl, D, Importer.getToContext(), DC, 5378 Importer.Import(D->getIdentifier()), Category->getClassInterface(), 5379 ToLocation, ToAtStartLoc, ToCategoryNameLoc)) 5380 return ToImpl; 5381 5382 ToImpl->setLexicalDeclContext(LexicalDC); 5383 LexicalDC->addDeclInternal(ToImpl); 5384 Category->setImplementation(ToImpl); 5385 } 5386 5387 Importer.MapImported(D, ToImpl); 5388 if (Error Err = ImportDeclContext(D)) 5389 return std::move(Err); 5390 5391 return ToImpl; 5392 } 5393 5394 ExpectedDecl 5395 ASTNodeImporter::VisitObjCImplementationDecl(ObjCImplementationDecl *D) { 5396 // Find the corresponding interface. 5397 ObjCInterfaceDecl *Iface; 5398 if (Error Err = importInto(Iface, D->getClassInterface())) 5399 return std::move(Err); 5400 5401 // Import the superclass, if any. 5402 ObjCInterfaceDecl *Super; 5403 if (Error Err = importInto(Super, D->getSuperClass())) 5404 return std::move(Err); 5405 5406 ObjCImplementationDecl *Impl = Iface->getImplementation(); 5407 if (!Impl) { 5408 // We haven't imported an implementation yet. Create a new @implementation 5409 // now. 5410 DeclContext *DC, *LexicalDC; 5411 if (Error Err = ImportDeclContext(D, DC, LexicalDC)) 5412 return std::move(Err); 5413 5414 Error Err = Error::success(); 5415 auto ToLocation = importChecked(Err, D->getLocation()); 5416 auto ToAtStartLoc = importChecked(Err, D->getAtStartLoc()); 5417 auto ToSuperClassLoc = importChecked(Err, D->getSuperClassLoc()); 5418 auto ToIvarLBraceLoc = importChecked(Err, D->getIvarLBraceLoc()); 5419 auto ToIvarRBraceLoc = importChecked(Err, D->getIvarRBraceLoc()); 5420 if (Err) 5421 return std::move(Err); 5422 5423 if (GetImportedOrCreateDecl(Impl, D, Importer.getToContext(), 5424 DC, Iface, Super, 5425 ToLocation, 5426 ToAtStartLoc, 5427 ToSuperClassLoc, 5428 ToIvarLBraceLoc, 5429 ToIvarRBraceLoc)) 5430 return Impl; 5431 5432 Impl->setLexicalDeclContext(LexicalDC); 5433 5434 // Associate the implementation with the class it implements. 5435 Iface->setImplementation(Impl); 5436 Importer.MapImported(D, Iface->getImplementation()); 5437 } else { 5438 Importer.MapImported(D, Iface->getImplementation()); 5439 5440 // Verify that the existing @implementation has the same superclass. 5441 if ((Super && !Impl->getSuperClass()) || 5442 (!Super && Impl->getSuperClass()) || 5443 (Super && Impl->getSuperClass() && 5444 !declaresSameEntity(Super->getCanonicalDecl(), 5445 Impl->getSuperClass()))) { 5446 Importer.ToDiag(Impl->getLocation(), 5447 diag::warn_odr_objc_superclass_inconsistent) 5448 << Iface->getDeclName(); 5449 // FIXME: It would be nice to have the location of the superclass 5450 // below. 5451 if (Impl->getSuperClass()) 5452 Importer.ToDiag(Impl->getLocation(), 5453 diag::note_odr_objc_superclass) 5454 << Impl->getSuperClass()->getDeclName(); 5455 else 5456 Importer.ToDiag(Impl->getLocation(), 5457 diag::note_odr_objc_missing_superclass); 5458 if (D->getSuperClass()) 5459 Importer.FromDiag(D->getLocation(), 5460 diag::note_odr_objc_superclass) 5461 << D->getSuperClass()->getDeclName(); 5462 else 5463 Importer.FromDiag(D->getLocation(), 5464 diag::note_odr_objc_missing_superclass); 5465 5466 return make_error<ASTImportError>(ASTImportError::NameConflict); 5467 } 5468 } 5469 5470 // Import all of the members of this @implementation. 5471 if (Error Err = ImportDeclContext(D)) 5472 return std::move(Err); 5473 5474 return Impl; 5475 } 5476 5477 ExpectedDecl ASTNodeImporter::VisitObjCPropertyDecl(ObjCPropertyDecl *D) { 5478 // Import the major distinguishing characteristics of an @property. 5479 DeclContext *DC, *LexicalDC; 5480 DeclarationName Name; 5481 SourceLocation Loc; 5482 NamedDecl *ToD; 5483 if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc)) 5484 return std::move(Err); 5485 if (ToD) 5486 return ToD; 5487 5488 // Check whether we have already imported this property. 5489 auto FoundDecls = Importer.findDeclsInToCtx(DC, Name); 5490 for (auto *FoundDecl : FoundDecls) { 5491 if (auto *FoundProp = dyn_cast<ObjCPropertyDecl>(FoundDecl)) { 5492 // Instance and class properties can share the same name but are different 5493 // declarations. 5494 if (FoundProp->isInstanceProperty() != D->isInstanceProperty()) 5495 continue; 5496 5497 // Check property types. 5498 if (!Importer.IsStructurallyEquivalent(D->getType(), 5499 FoundProp->getType())) { 5500 Importer.ToDiag(Loc, diag::warn_odr_objc_property_type_inconsistent) 5501 << Name << D->getType() << FoundProp->getType(); 5502 Importer.ToDiag(FoundProp->getLocation(), diag::note_odr_value_here) 5503 << FoundProp->getType(); 5504 5505 return make_error<ASTImportError>(ASTImportError::NameConflict); 5506 } 5507 5508 // FIXME: Check property attributes, getters, setters, etc.? 5509 5510 // Consider these properties to be equivalent. 5511 Importer.MapImported(D, FoundProp); 5512 return FoundProp; 5513 } 5514 } 5515 5516 Error Err = Error::success(); 5517 auto ToType = importChecked(Err, D->getType()); 5518 auto ToTypeSourceInfo = importChecked(Err, D->getTypeSourceInfo()); 5519 auto ToAtLoc = importChecked(Err, D->getAtLoc()); 5520 auto ToLParenLoc = importChecked(Err, D->getLParenLoc()); 5521 if (Err) 5522 return std::move(Err); 5523 5524 // Create the new property. 5525 ObjCPropertyDecl *ToProperty; 5526 if (GetImportedOrCreateDecl( 5527 ToProperty, D, Importer.getToContext(), DC, Loc, 5528 Name.getAsIdentifierInfo(), ToAtLoc, 5529 ToLParenLoc, ToType, 5530 ToTypeSourceInfo, D->getPropertyImplementation())) 5531 return ToProperty; 5532 5533 auto ToGetterName = importChecked(Err, D->getGetterName()); 5534 auto ToSetterName = importChecked(Err, D->getSetterName()); 5535 auto ToGetterNameLoc = importChecked(Err, D->getGetterNameLoc()); 5536 auto ToSetterNameLoc = importChecked(Err, D->getSetterNameLoc()); 5537 auto ToGetterMethodDecl = importChecked(Err, D->getGetterMethodDecl()); 5538 auto ToSetterMethodDecl = importChecked(Err, D->getSetterMethodDecl()); 5539 auto ToPropertyIvarDecl = importChecked(Err, D->getPropertyIvarDecl()); 5540 if (Err) 5541 return std::move(Err); 5542 5543 ToProperty->setLexicalDeclContext(LexicalDC); 5544 LexicalDC->addDeclInternal(ToProperty); 5545 5546 ToProperty->setPropertyAttributes(D->getPropertyAttributes()); 5547 ToProperty->setPropertyAttributesAsWritten( 5548 D->getPropertyAttributesAsWritten()); 5549 ToProperty->setGetterName(ToGetterName, ToGetterNameLoc); 5550 ToProperty->setSetterName(ToSetterName, ToSetterNameLoc); 5551 ToProperty->setGetterMethodDecl(ToGetterMethodDecl); 5552 ToProperty->setSetterMethodDecl(ToSetterMethodDecl); 5553 ToProperty->setPropertyIvarDecl(ToPropertyIvarDecl); 5554 return ToProperty; 5555 } 5556 5557 ExpectedDecl 5558 ASTNodeImporter::VisitObjCPropertyImplDecl(ObjCPropertyImplDecl *D) { 5559 ObjCPropertyDecl *Property; 5560 if (Error Err = importInto(Property, D->getPropertyDecl())) 5561 return std::move(Err); 5562 5563 DeclContext *DC, *LexicalDC; 5564 if (Error Err = ImportDeclContext(D, DC, LexicalDC)) 5565 return std::move(Err); 5566 5567 auto *InImpl = cast<ObjCImplDecl>(LexicalDC); 5568 5569 // Import the ivar (for an @synthesize). 5570 ObjCIvarDecl *Ivar = nullptr; 5571 if (Error Err = importInto(Ivar, D->getPropertyIvarDecl())) 5572 return std::move(Err); 5573 5574 ObjCPropertyImplDecl *ToImpl 5575 = InImpl->FindPropertyImplDecl(Property->getIdentifier(), 5576 Property->getQueryKind()); 5577 if (!ToImpl) { 5578 5579 Error Err = Error::success(); 5580 auto ToBeginLoc = importChecked(Err, D->getBeginLoc()); 5581 auto ToLocation = importChecked(Err, D->getLocation()); 5582 auto ToPropertyIvarDeclLoc = 5583 importChecked(Err, D->getPropertyIvarDeclLoc()); 5584 if (Err) 5585 return std::move(Err); 5586 5587 if (GetImportedOrCreateDecl(ToImpl, D, Importer.getToContext(), DC, 5588 ToBeginLoc, 5589 ToLocation, Property, 5590 D->getPropertyImplementation(), Ivar, 5591 ToPropertyIvarDeclLoc)) 5592 return ToImpl; 5593 5594 ToImpl->setLexicalDeclContext(LexicalDC); 5595 LexicalDC->addDeclInternal(ToImpl); 5596 } else { 5597 // Check that we have the same kind of property implementation (@synthesize 5598 // vs. @dynamic). 5599 if (D->getPropertyImplementation() != ToImpl->getPropertyImplementation()) { 5600 Importer.ToDiag(ToImpl->getLocation(), 5601 diag::warn_odr_objc_property_impl_kind_inconsistent) 5602 << Property->getDeclName() 5603 << (ToImpl->getPropertyImplementation() 5604 == ObjCPropertyImplDecl::Dynamic); 5605 Importer.FromDiag(D->getLocation(), 5606 diag::note_odr_objc_property_impl_kind) 5607 << D->getPropertyDecl()->getDeclName() 5608 << (D->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic); 5609 5610 return make_error<ASTImportError>(ASTImportError::NameConflict); 5611 } 5612 5613 // For @synthesize, check that we have the same 5614 if (D->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize && 5615 Ivar != ToImpl->getPropertyIvarDecl()) { 5616 Importer.ToDiag(ToImpl->getPropertyIvarDeclLoc(), 5617 diag::warn_odr_objc_synthesize_ivar_inconsistent) 5618 << Property->getDeclName() 5619 << ToImpl->getPropertyIvarDecl()->getDeclName() 5620 << Ivar->getDeclName(); 5621 Importer.FromDiag(D->getPropertyIvarDeclLoc(), 5622 diag::note_odr_objc_synthesize_ivar_here) 5623 << D->getPropertyIvarDecl()->getDeclName(); 5624 5625 return make_error<ASTImportError>(ASTImportError::NameConflict); 5626 } 5627 5628 // Merge the existing implementation with the new implementation. 5629 Importer.MapImported(D, ToImpl); 5630 } 5631 5632 return ToImpl; 5633 } 5634 5635 ExpectedDecl 5636 ASTNodeImporter::VisitTemplateTypeParmDecl(TemplateTypeParmDecl *D) { 5637 // For template arguments, we adopt the translation unit as our declaration 5638 // context. This context will be fixed when the actual template declaration 5639 // is created. 5640 5641 ExpectedSLoc BeginLocOrErr = import(D->getBeginLoc()); 5642 if (!BeginLocOrErr) 5643 return BeginLocOrErr.takeError(); 5644 5645 ExpectedSLoc LocationOrErr = import(D->getLocation()); 5646 if (!LocationOrErr) 5647 return LocationOrErr.takeError(); 5648 5649 TemplateTypeParmDecl *ToD = nullptr; 5650 if (GetImportedOrCreateDecl( 5651 ToD, D, Importer.getToContext(), 5652 Importer.getToContext().getTranslationUnitDecl(), 5653 *BeginLocOrErr, *LocationOrErr, 5654 D->getDepth(), D->getIndex(), Importer.Import(D->getIdentifier()), 5655 D->wasDeclaredWithTypename(), D->isParameterPack(), 5656 D->hasTypeConstraint())) 5657 return ToD; 5658 5659 // Import the type-constraint 5660 if (const TypeConstraint *TC = D->getTypeConstraint()) { 5661 5662 Error Err = Error::success(); 5663 auto ToNNS = importChecked(Err, TC->getNestedNameSpecifierLoc()); 5664 auto ToName = importChecked(Err, TC->getConceptNameInfo().getName()); 5665 auto ToNameLoc = importChecked(Err, TC->getConceptNameInfo().getLoc()); 5666 auto ToFoundDecl = importChecked(Err, TC->getFoundDecl()); 5667 auto ToNamedConcept = importChecked(Err, TC->getNamedConcept()); 5668 auto ToIDC = importChecked(Err, TC->getImmediatelyDeclaredConstraint()); 5669 if (Err) 5670 return std::move(Err); 5671 5672 TemplateArgumentListInfo ToTAInfo; 5673 const auto *ASTTemplateArgs = TC->getTemplateArgsAsWritten(); 5674 if (ASTTemplateArgs) 5675 if (Error Err = ImportTemplateArgumentListInfo(*ASTTemplateArgs, 5676 ToTAInfo)) 5677 return std::move(Err); 5678 5679 ToD->setTypeConstraint(ToNNS, DeclarationNameInfo(ToName, ToNameLoc), 5680 ToFoundDecl, ToNamedConcept, 5681 ASTTemplateArgs ? 5682 ASTTemplateArgumentListInfo::Create(Importer.getToContext(), 5683 ToTAInfo) : nullptr, 5684 ToIDC); 5685 } 5686 5687 if (D->hasDefaultArgument()) { 5688 Expected<TypeSourceInfo *> ToDefaultArgOrErr = 5689 import(D->getDefaultArgumentInfo()); 5690 if (!ToDefaultArgOrErr) 5691 return ToDefaultArgOrErr.takeError(); 5692 ToD->setDefaultArgument(*ToDefaultArgOrErr); 5693 } 5694 5695 return ToD; 5696 } 5697 5698 ExpectedDecl 5699 ASTNodeImporter::VisitNonTypeTemplateParmDecl(NonTypeTemplateParmDecl *D) { 5700 5701 Error Err = Error::success(); 5702 auto ToDeclName = importChecked(Err, D->getDeclName()); 5703 auto ToLocation = importChecked(Err, D->getLocation()); 5704 auto ToType = importChecked(Err, D->getType()); 5705 auto ToTypeSourceInfo = importChecked(Err, D->getTypeSourceInfo()); 5706 auto ToInnerLocStart = importChecked(Err, D->getInnerLocStart()); 5707 if (Err) 5708 return std::move(Err); 5709 5710 NonTypeTemplateParmDecl *ToD = nullptr; 5711 if (GetImportedOrCreateDecl(ToD, D, Importer.getToContext(), 5712 Importer.getToContext().getTranslationUnitDecl(), 5713 ToInnerLocStart, ToLocation, D->getDepth(), 5714 D->getPosition(), 5715 ToDeclName.getAsIdentifierInfo(), ToType, 5716 D->isParameterPack(), ToTypeSourceInfo)) 5717 return ToD; 5718 5719 if (D->hasDefaultArgument()) { 5720 ExpectedExpr ToDefaultArgOrErr = import(D->getDefaultArgument()); 5721 if (!ToDefaultArgOrErr) 5722 return ToDefaultArgOrErr.takeError(); 5723 ToD->setDefaultArgument(*ToDefaultArgOrErr); 5724 } 5725 5726 return ToD; 5727 } 5728 5729 ExpectedDecl 5730 ASTNodeImporter::VisitTemplateTemplateParmDecl(TemplateTemplateParmDecl *D) { 5731 // Import the name of this declaration. 5732 auto NameOrErr = import(D->getDeclName()); 5733 if (!NameOrErr) 5734 return NameOrErr.takeError(); 5735 5736 // Import the location of this declaration. 5737 ExpectedSLoc LocationOrErr = import(D->getLocation()); 5738 if (!LocationOrErr) 5739 return LocationOrErr.takeError(); 5740 5741 // Import template parameters. 5742 auto TemplateParamsOrErr = import(D->getTemplateParameters()); 5743 if (!TemplateParamsOrErr) 5744 return TemplateParamsOrErr.takeError(); 5745 5746 TemplateTemplateParmDecl *ToD = nullptr; 5747 if (GetImportedOrCreateDecl( 5748 ToD, D, Importer.getToContext(), 5749 Importer.getToContext().getTranslationUnitDecl(), *LocationOrErr, 5750 D->getDepth(), D->getPosition(), D->isParameterPack(), 5751 (*NameOrErr).getAsIdentifierInfo(), *TemplateParamsOrErr)) 5752 return ToD; 5753 5754 if (D->hasDefaultArgument()) { 5755 Expected<TemplateArgumentLoc> ToDefaultArgOrErr = 5756 import(D->getDefaultArgument()); 5757 if (!ToDefaultArgOrErr) 5758 return ToDefaultArgOrErr.takeError(); 5759 ToD->setDefaultArgument(Importer.getToContext(), *ToDefaultArgOrErr); 5760 } 5761 5762 return ToD; 5763 } 5764 5765 // Returns the definition for a (forward) declaration of a TemplateDecl, if 5766 // it has any definition in the redecl chain. 5767 template <typename T> static auto getTemplateDefinition(T *D) -> T * { 5768 assert(D->getTemplatedDecl() && "Should be called on templates only"); 5769 auto *ToTemplatedDef = D->getTemplatedDecl()->getDefinition(); 5770 if (!ToTemplatedDef) 5771 return nullptr; 5772 auto *TemplateWithDef = ToTemplatedDef->getDescribedTemplate(); 5773 return cast_or_null<T>(TemplateWithDef); 5774 } 5775 5776 ExpectedDecl ASTNodeImporter::VisitClassTemplateDecl(ClassTemplateDecl *D) { 5777 5778 // Import the major distinguishing characteristics of this class template. 5779 DeclContext *DC, *LexicalDC; 5780 DeclarationName Name; 5781 SourceLocation Loc; 5782 NamedDecl *ToD; 5783 if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc)) 5784 return std::move(Err); 5785 if (ToD) 5786 return ToD; 5787 5788 ClassTemplateDecl *FoundByLookup = nullptr; 5789 5790 // We may already have a template of the same name; try to find and match it. 5791 if (!DC->isFunctionOrMethod()) { 5792 SmallVector<NamedDecl *, 4> ConflictingDecls; 5793 auto FoundDecls = Importer.findDeclsInToCtx(DC, Name); 5794 for (auto *FoundDecl : FoundDecls) { 5795 if (!FoundDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary | 5796 Decl::IDNS_TagFriend)) 5797 continue; 5798 5799 Decl *Found = FoundDecl; 5800 auto *FoundTemplate = dyn_cast<ClassTemplateDecl>(Found); 5801 if (FoundTemplate) { 5802 if (!hasSameVisibilityContextAndLinkage(FoundTemplate, D)) 5803 continue; 5804 5805 if (IsStructuralMatch(D, FoundTemplate)) { 5806 ClassTemplateDecl *TemplateWithDef = 5807 getTemplateDefinition(FoundTemplate); 5808 if (D->isThisDeclarationADefinition() && TemplateWithDef) 5809 return Importer.MapImported(D, TemplateWithDef); 5810 if (!FoundByLookup) 5811 FoundByLookup = FoundTemplate; 5812 // Search in all matches because there may be multiple decl chains, 5813 // see ASTTests test ImportExistingFriendClassTemplateDef. 5814 continue; 5815 } 5816 ConflictingDecls.push_back(FoundDecl); 5817 } 5818 } 5819 5820 if (!ConflictingDecls.empty()) { 5821 ExpectedName NameOrErr = Importer.HandleNameConflict( 5822 Name, DC, Decl::IDNS_Ordinary, ConflictingDecls.data(), 5823 ConflictingDecls.size()); 5824 if (NameOrErr) 5825 Name = NameOrErr.get(); 5826 else 5827 return NameOrErr.takeError(); 5828 } 5829 } 5830 5831 CXXRecordDecl *FromTemplated = D->getTemplatedDecl(); 5832 5833 auto TemplateParamsOrErr = import(D->getTemplateParameters()); 5834 if (!TemplateParamsOrErr) 5835 return TemplateParamsOrErr.takeError(); 5836 5837 // Create the declaration that is being templated. 5838 CXXRecordDecl *ToTemplated; 5839 if (Error Err = importInto(ToTemplated, FromTemplated)) 5840 return std::move(Err); 5841 5842 // Create the class template declaration itself. 5843 ClassTemplateDecl *D2; 5844 if (GetImportedOrCreateDecl(D2, D, Importer.getToContext(), DC, Loc, Name, 5845 *TemplateParamsOrErr, ToTemplated)) 5846 return D2; 5847 5848 ToTemplated->setDescribedClassTemplate(D2); 5849 5850 D2->setAccess(D->getAccess()); 5851 D2->setLexicalDeclContext(LexicalDC); 5852 5853 addDeclToContexts(D, D2); 5854 updateLookupTableForTemplateParameters(**TemplateParamsOrErr); 5855 5856 if (FoundByLookup) { 5857 auto *Recent = 5858 const_cast<ClassTemplateDecl *>(FoundByLookup->getMostRecentDecl()); 5859 5860 // It is possible that during the import of the class template definition 5861 // we start the import of a fwd friend decl of the very same class template 5862 // and we add the fwd friend decl to the lookup table. But the ToTemplated 5863 // had been created earlier and by that time the lookup could not find 5864 // anything existing, so it has no previous decl. Later, (still during the 5865 // import of the fwd friend decl) we start to import the definition again 5866 // and this time the lookup finds the previous fwd friend class template. 5867 // In this case we must set up the previous decl for the templated decl. 5868 if (!ToTemplated->getPreviousDecl()) { 5869 assert(FoundByLookup->getTemplatedDecl() && 5870 "Found decl must have its templated decl set"); 5871 CXXRecordDecl *PrevTemplated = 5872 FoundByLookup->getTemplatedDecl()->getMostRecentDecl(); 5873 if (ToTemplated != PrevTemplated) 5874 ToTemplated->setPreviousDecl(PrevTemplated); 5875 } 5876 5877 D2->setPreviousDecl(Recent); 5878 } 5879 5880 return D2; 5881 } 5882 5883 ExpectedDecl ASTNodeImporter::VisitClassTemplateSpecializationDecl( 5884 ClassTemplateSpecializationDecl *D) { 5885 ClassTemplateDecl *ClassTemplate; 5886 if (Error Err = importInto(ClassTemplate, D->getSpecializedTemplate())) 5887 return std::move(Err); 5888 5889 // Import the context of this declaration. 5890 DeclContext *DC, *LexicalDC; 5891 if (Error Err = ImportDeclContext(D, DC, LexicalDC)) 5892 return std::move(Err); 5893 5894 // Import template arguments. 5895 SmallVector<TemplateArgument, 2> TemplateArgs; 5896 if (Error Err = 5897 ImportTemplateArguments(D->getTemplateArgs().asArray(), TemplateArgs)) 5898 return std::move(Err); 5899 // Try to find an existing specialization with these template arguments and 5900 // template parameter list. 5901 void *InsertPos = nullptr; 5902 ClassTemplateSpecializationDecl *PrevDecl = nullptr; 5903 ClassTemplatePartialSpecializationDecl *PartialSpec = 5904 dyn_cast<ClassTemplatePartialSpecializationDecl>(D); 5905 5906 // Import template parameters. 5907 TemplateParameterList *ToTPList = nullptr; 5908 5909 if (PartialSpec) { 5910 auto ToTPListOrErr = import(PartialSpec->getTemplateParameters()); 5911 if (!ToTPListOrErr) 5912 return ToTPListOrErr.takeError(); 5913 ToTPList = *ToTPListOrErr; 5914 PrevDecl = ClassTemplate->findPartialSpecialization(TemplateArgs, 5915 *ToTPListOrErr, 5916 InsertPos); 5917 } else 5918 PrevDecl = ClassTemplate->findSpecialization(TemplateArgs, InsertPos); 5919 5920 if (PrevDecl) { 5921 if (IsStructuralMatch(D, PrevDecl)) { 5922 CXXRecordDecl *PrevDefinition = PrevDecl->getDefinition(); 5923 if (D->isThisDeclarationADefinition() && PrevDefinition) { 5924 Importer.MapImported(D, PrevDefinition); 5925 // Import those default field initializers which have been 5926 // instantiated in the "From" context, but not in the "To" context. 5927 for (auto *FromField : D->fields()) { 5928 auto ToOrErr = import(FromField); 5929 if (!ToOrErr) 5930 return ToOrErr.takeError(); 5931 } 5932 5933 // Import those methods which have been instantiated in the 5934 // "From" context, but not in the "To" context. 5935 for (CXXMethodDecl *FromM : D->methods()) { 5936 auto ToOrErr = import(FromM); 5937 if (!ToOrErr) 5938 return ToOrErr.takeError(); 5939 } 5940 5941 // TODO Import instantiated default arguments. 5942 // TODO Import instantiated exception specifications. 5943 // 5944 // Generally, ASTCommon.h/DeclUpdateKind enum gives a very good hint 5945 // what else could be fused during an AST merge. 5946 return PrevDefinition; 5947 } 5948 } else { // ODR violation. 5949 // FIXME HandleNameConflict 5950 return make_error<ASTImportError>(ASTImportError::NameConflict); 5951 } 5952 } 5953 5954 // Import the location of this declaration. 5955 ExpectedSLoc BeginLocOrErr = import(D->getBeginLoc()); 5956 if (!BeginLocOrErr) 5957 return BeginLocOrErr.takeError(); 5958 ExpectedSLoc IdLocOrErr = import(D->getLocation()); 5959 if (!IdLocOrErr) 5960 return IdLocOrErr.takeError(); 5961 5962 // Create the specialization. 5963 ClassTemplateSpecializationDecl *D2 = nullptr; 5964 if (PartialSpec) { 5965 // Import TemplateArgumentListInfo. 5966 TemplateArgumentListInfo ToTAInfo; 5967 const auto &ASTTemplateArgs = *PartialSpec->getTemplateArgsAsWritten(); 5968 if (Error Err = ImportTemplateArgumentListInfo(ASTTemplateArgs, ToTAInfo)) 5969 return std::move(Err); 5970 5971 QualType CanonInjType; 5972 if (Error Err = importInto( 5973 CanonInjType, PartialSpec->getInjectedSpecializationType())) 5974 return std::move(Err); 5975 CanonInjType = CanonInjType.getCanonicalType(); 5976 5977 if (GetImportedOrCreateDecl<ClassTemplatePartialSpecializationDecl>( 5978 D2, D, Importer.getToContext(), D->getTagKind(), DC, *BeginLocOrErr, 5979 *IdLocOrErr, ToTPList, ClassTemplate, 5980 llvm::ArrayRef(TemplateArgs.data(), TemplateArgs.size()), ToTAInfo, 5981 CanonInjType, 5982 cast_or_null<ClassTemplatePartialSpecializationDecl>(PrevDecl))) 5983 return D2; 5984 5985 // Update InsertPos, because preceding import calls may have invalidated 5986 // it by adding new specializations. 5987 auto *PartSpec2 = cast<ClassTemplatePartialSpecializationDecl>(D2); 5988 if (!ClassTemplate->findPartialSpecialization(TemplateArgs, ToTPList, 5989 InsertPos)) 5990 // Add this partial specialization to the class template. 5991 ClassTemplate->AddPartialSpecialization(PartSpec2, InsertPos); 5992 5993 updateLookupTableForTemplateParameters(*ToTPList); 5994 } else { // Not a partial specialization. 5995 if (GetImportedOrCreateDecl( 5996 D2, D, Importer.getToContext(), D->getTagKind(), DC, 5997 *BeginLocOrErr, *IdLocOrErr, ClassTemplate, TemplateArgs, 5998 PrevDecl)) 5999 return D2; 6000 6001 // Update InsertPos, because preceding import calls may have invalidated 6002 // it by adding new specializations. 6003 if (!ClassTemplate->findSpecialization(TemplateArgs, InsertPos)) 6004 // Add this specialization to the class template. 6005 ClassTemplate->AddSpecialization(D2, InsertPos); 6006 } 6007 6008 D2->setSpecializationKind(D->getSpecializationKind()); 6009 6010 // Set the context of this specialization/instantiation. 6011 D2->setLexicalDeclContext(LexicalDC); 6012 6013 // Add to the DC only if it was an explicit specialization/instantiation. 6014 if (D2->isExplicitInstantiationOrSpecialization()) { 6015 LexicalDC->addDeclInternal(D2); 6016 } 6017 6018 if (auto BraceRangeOrErr = import(D->getBraceRange())) 6019 D2->setBraceRange(*BraceRangeOrErr); 6020 else 6021 return BraceRangeOrErr.takeError(); 6022 6023 // Import the qualifier, if any. 6024 if (auto LocOrErr = import(D->getQualifierLoc())) 6025 D2->setQualifierInfo(*LocOrErr); 6026 else 6027 return LocOrErr.takeError(); 6028 6029 if (auto *TSI = D->getTypeAsWritten()) { 6030 if (auto TInfoOrErr = import(TSI)) 6031 D2->setTypeAsWritten(*TInfoOrErr); 6032 else 6033 return TInfoOrErr.takeError(); 6034 6035 if (auto LocOrErr = import(D->getTemplateKeywordLoc())) 6036 D2->setTemplateKeywordLoc(*LocOrErr); 6037 else 6038 return LocOrErr.takeError(); 6039 6040 if (auto LocOrErr = import(D->getExternLoc())) 6041 D2->setExternLoc(*LocOrErr); 6042 else 6043 return LocOrErr.takeError(); 6044 } 6045 6046 if (D->getPointOfInstantiation().isValid()) { 6047 if (auto POIOrErr = import(D->getPointOfInstantiation())) 6048 D2->setPointOfInstantiation(*POIOrErr); 6049 else 6050 return POIOrErr.takeError(); 6051 } 6052 6053 D2->setTemplateSpecializationKind(D->getTemplateSpecializationKind()); 6054 6055 if (auto P = D->getInstantiatedFrom()) { 6056 if (auto *CTD = P.dyn_cast<ClassTemplateDecl *>()) { 6057 if (auto CTDorErr = import(CTD)) 6058 D2->setInstantiationOf(*CTDorErr); 6059 } else { 6060 auto *CTPSD = cast<ClassTemplatePartialSpecializationDecl *>(P); 6061 auto CTPSDOrErr = import(CTPSD); 6062 if (!CTPSDOrErr) 6063 return CTPSDOrErr.takeError(); 6064 const TemplateArgumentList &DArgs = D->getTemplateInstantiationArgs(); 6065 SmallVector<TemplateArgument, 2> D2ArgsVec(DArgs.size()); 6066 for (unsigned I = 0; I < DArgs.size(); ++I) { 6067 const TemplateArgument &DArg = DArgs[I]; 6068 if (auto ArgOrErr = import(DArg)) 6069 D2ArgsVec[I] = *ArgOrErr; 6070 else 6071 return ArgOrErr.takeError(); 6072 } 6073 D2->setInstantiationOf( 6074 *CTPSDOrErr, 6075 TemplateArgumentList::CreateCopy(Importer.getToContext(), D2ArgsVec)); 6076 } 6077 } 6078 6079 if (D->isCompleteDefinition()) 6080 if (Error Err = ImportDefinition(D, D2)) 6081 return std::move(Err); 6082 6083 return D2; 6084 } 6085 6086 ExpectedDecl ASTNodeImporter::VisitVarTemplateDecl(VarTemplateDecl *D) { 6087 // Import the major distinguishing characteristics of this variable template. 6088 DeclContext *DC, *LexicalDC; 6089 DeclarationName Name; 6090 SourceLocation Loc; 6091 NamedDecl *ToD; 6092 if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc)) 6093 return std::move(Err); 6094 if (ToD) 6095 return ToD; 6096 6097 // We may already have a template of the same name; try to find and match it. 6098 assert(!DC->isFunctionOrMethod() && 6099 "Variable templates cannot be declared at function scope"); 6100 6101 SmallVector<NamedDecl *, 4> ConflictingDecls; 6102 auto FoundDecls = Importer.findDeclsInToCtx(DC, Name); 6103 VarTemplateDecl *FoundByLookup = nullptr; 6104 for (auto *FoundDecl : FoundDecls) { 6105 if (!FoundDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary)) 6106 continue; 6107 6108 if (VarTemplateDecl *FoundTemplate = dyn_cast<VarTemplateDecl>(FoundDecl)) { 6109 // Use the templated decl, some linkage flags are set only there. 6110 if (!hasSameVisibilityContextAndLinkage(FoundTemplate->getTemplatedDecl(), 6111 D->getTemplatedDecl())) 6112 continue; 6113 if (IsStructuralMatch(D, FoundTemplate)) { 6114 // The Decl in the "From" context has a definition, but in the 6115 // "To" context we already have a definition. 6116 VarTemplateDecl *FoundDef = getTemplateDefinition(FoundTemplate); 6117 if (D->isThisDeclarationADefinition() && FoundDef) 6118 // FIXME Check for ODR error if the two definitions have 6119 // different initializers? 6120 return Importer.MapImported(D, FoundDef); 6121 6122 FoundByLookup = FoundTemplate; 6123 break; 6124 } 6125 ConflictingDecls.push_back(FoundDecl); 6126 } 6127 } 6128 6129 if (!ConflictingDecls.empty()) { 6130 ExpectedName NameOrErr = Importer.HandleNameConflict( 6131 Name, DC, Decl::IDNS_Ordinary, ConflictingDecls.data(), 6132 ConflictingDecls.size()); 6133 if (NameOrErr) 6134 Name = NameOrErr.get(); 6135 else 6136 return NameOrErr.takeError(); 6137 } 6138 6139 VarDecl *DTemplated = D->getTemplatedDecl(); 6140 6141 // Import the type. 6142 // FIXME: Value not used? 6143 ExpectedType TypeOrErr = import(DTemplated->getType()); 6144 if (!TypeOrErr) 6145 return TypeOrErr.takeError(); 6146 6147 // Create the declaration that is being templated. 6148 VarDecl *ToTemplated; 6149 if (Error Err = importInto(ToTemplated, DTemplated)) 6150 return std::move(Err); 6151 6152 // Create the variable template declaration itself. 6153 auto TemplateParamsOrErr = import(D->getTemplateParameters()); 6154 if (!TemplateParamsOrErr) 6155 return TemplateParamsOrErr.takeError(); 6156 6157 VarTemplateDecl *ToVarTD; 6158 if (GetImportedOrCreateDecl(ToVarTD, D, Importer.getToContext(), DC, Loc, 6159 Name, *TemplateParamsOrErr, ToTemplated)) 6160 return ToVarTD; 6161 6162 ToTemplated->setDescribedVarTemplate(ToVarTD); 6163 6164 ToVarTD->setAccess(D->getAccess()); 6165 ToVarTD->setLexicalDeclContext(LexicalDC); 6166 LexicalDC->addDeclInternal(ToVarTD); 6167 if (DC != Importer.getToContext().getTranslationUnitDecl()) 6168 updateLookupTableForTemplateParameters(**TemplateParamsOrErr); 6169 6170 if (FoundByLookup) { 6171 auto *Recent = 6172 const_cast<VarTemplateDecl *>(FoundByLookup->getMostRecentDecl()); 6173 if (!ToTemplated->getPreviousDecl()) { 6174 auto *PrevTemplated = 6175 FoundByLookup->getTemplatedDecl()->getMostRecentDecl(); 6176 if (ToTemplated != PrevTemplated) 6177 ToTemplated->setPreviousDecl(PrevTemplated); 6178 } 6179 ToVarTD->setPreviousDecl(Recent); 6180 } 6181 6182 return ToVarTD; 6183 } 6184 6185 ExpectedDecl ASTNodeImporter::VisitVarTemplateSpecializationDecl( 6186 VarTemplateSpecializationDecl *D) { 6187 // If this record has a definition in the translation unit we're coming from, 6188 // but this particular declaration is not that definition, import the 6189 // definition and map to that. 6190 VarDecl *Definition = D->getDefinition(); 6191 if (Definition && Definition != D) { 6192 if (ExpectedDecl ImportedDefOrErr = import(Definition)) 6193 return Importer.MapImported(D, *ImportedDefOrErr); 6194 else 6195 return ImportedDefOrErr.takeError(); 6196 } 6197 6198 VarTemplateDecl *VarTemplate = nullptr; 6199 if (Error Err = importInto(VarTemplate, D->getSpecializedTemplate())) 6200 return std::move(Err); 6201 6202 // Import the context of this declaration. 6203 DeclContext *DC, *LexicalDC; 6204 if (Error Err = ImportDeclContext(D, DC, LexicalDC)) 6205 return std::move(Err); 6206 6207 // Import the location of this declaration. 6208 ExpectedSLoc BeginLocOrErr = import(D->getBeginLoc()); 6209 if (!BeginLocOrErr) 6210 return BeginLocOrErr.takeError(); 6211 6212 auto IdLocOrErr = import(D->getLocation()); 6213 if (!IdLocOrErr) 6214 return IdLocOrErr.takeError(); 6215 6216 // Import template arguments. 6217 SmallVector<TemplateArgument, 2> TemplateArgs; 6218 if (Error Err = 6219 ImportTemplateArguments(D->getTemplateArgs().asArray(), TemplateArgs)) 6220 return std::move(Err); 6221 6222 // Try to find an existing specialization with these template arguments. 6223 void *InsertPos = nullptr; 6224 VarTemplateSpecializationDecl *D2 = VarTemplate->findSpecialization( 6225 TemplateArgs, InsertPos); 6226 if (D2) { 6227 // We already have a variable template specialization with these template 6228 // arguments. 6229 6230 // FIXME: Check for specialization vs. instantiation errors. 6231 6232 if (VarDecl *FoundDef = D2->getDefinition()) { 6233 if (!D->isThisDeclarationADefinition() || 6234 IsStructuralMatch(D, FoundDef)) { 6235 // The record types structurally match, or the "from" translation 6236 // unit only had a forward declaration anyway; call it the same 6237 // variable. 6238 return Importer.MapImported(D, FoundDef); 6239 } 6240 } 6241 } else { 6242 TemplateArgumentListInfo ToTAInfo; 6243 if (const ASTTemplateArgumentListInfo *Args = D->getTemplateArgsInfo()) { 6244 if (Error Err = ImportTemplateArgumentListInfo(*Args, ToTAInfo)) 6245 return std::move(Err); 6246 } 6247 6248 using PartVarSpecDecl = VarTemplatePartialSpecializationDecl; 6249 // Create a new specialization. 6250 if (auto *FromPartial = dyn_cast<PartVarSpecDecl>(D)) { 6251 // Import TemplateArgumentListInfo 6252 TemplateArgumentListInfo ArgInfos; 6253 const auto *FromTAArgsAsWritten = FromPartial->getTemplateArgsAsWritten(); 6254 // NOTE: FromTAArgsAsWritten and template parameter list are non-null. 6255 if (Error Err = ImportTemplateArgumentListInfo( 6256 *FromTAArgsAsWritten, ArgInfos)) 6257 return std::move(Err); 6258 6259 auto ToTPListOrErr = import(FromPartial->getTemplateParameters()); 6260 if (!ToTPListOrErr) 6261 return ToTPListOrErr.takeError(); 6262 6263 PartVarSpecDecl *ToPartial; 6264 if (GetImportedOrCreateDecl(ToPartial, D, Importer.getToContext(), DC, 6265 *BeginLocOrErr, *IdLocOrErr, *ToTPListOrErr, 6266 VarTemplate, QualType(), nullptr, 6267 D->getStorageClass(), TemplateArgs, ArgInfos)) 6268 return ToPartial; 6269 6270 if (Expected<PartVarSpecDecl *> ToInstOrErr = import( 6271 FromPartial->getInstantiatedFromMember())) 6272 ToPartial->setInstantiatedFromMember(*ToInstOrErr); 6273 else 6274 return ToInstOrErr.takeError(); 6275 6276 if (FromPartial->isMemberSpecialization()) 6277 ToPartial->setMemberSpecialization(); 6278 6279 D2 = ToPartial; 6280 6281 // FIXME: Use this update if VarTemplatePartialSpecializationDecl is fixed 6282 // to adopt template parameters. 6283 // updateLookupTableForTemplateParameters(**ToTPListOrErr); 6284 } else { // Full specialization 6285 if (GetImportedOrCreateDecl(D2, D, Importer.getToContext(), DC, 6286 *BeginLocOrErr, *IdLocOrErr, VarTemplate, 6287 QualType(), nullptr, D->getStorageClass(), 6288 TemplateArgs)) 6289 return D2; 6290 } 6291 6292 QualType T; 6293 if (Error Err = importInto(T, D->getType())) 6294 return std::move(Err); 6295 D2->setType(T); 6296 6297 auto TInfoOrErr = import(D->getTypeSourceInfo()); 6298 if (!TInfoOrErr) 6299 return TInfoOrErr.takeError(); 6300 D2->setTypeSourceInfo(*TInfoOrErr); 6301 6302 if (D->getPointOfInstantiation().isValid()) { 6303 if (ExpectedSLoc POIOrErr = import(D->getPointOfInstantiation())) 6304 D2->setPointOfInstantiation(*POIOrErr); 6305 else 6306 return POIOrErr.takeError(); 6307 } 6308 6309 D2->setSpecializationKind(D->getSpecializationKind()); 6310 D2->setTemplateArgsInfo(ToTAInfo); 6311 6312 // Add this specialization to the class template. 6313 VarTemplate->AddSpecialization(D2, InsertPos); 6314 6315 // Import the qualifier, if any. 6316 if (auto LocOrErr = import(D->getQualifierLoc())) 6317 D2->setQualifierInfo(*LocOrErr); 6318 else 6319 return LocOrErr.takeError(); 6320 6321 if (D->isConstexpr()) 6322 D2->setConstexpr(true); 6323 6324 // Add the specialization to this context. 6325 D2->setLexicalDeclContext(LexicalDC); 6326 LexicalDC->addDeclInternal(D2); 6327 6328 D2->setAccess(D->getAccess()); 6329 } 6330 6331 if (Error Err = ImportInitializer(D, D2)) 6332 return std::move(Err); 6333 6334 return D2; 6335 } 6336 6337 ExpectedDecl 6338 ASTNodeImporter::VisitFunctionTemplateDecl(FunctionTemplateDecl *D) { 6339 DeclContext *DC, *LexicalDC; 6340 DeclarationName Name; 6341 SourceLocation Loc; 6342 NamedDecl *ToD; 6343 6344 if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc)) 6345 return std::move(Err); 6346 6347 if (ToD) 6348 return ToD; 6349 6350 const FunctionTemplateDecl *FoundByLookup = nullptr; 6351 6352 // Try to find a function in our own ("to") context with the same name, same 6353 // type, and in the same context as the function we're importing. 6354 // FIXME Split this into a separate function. 6355 if (!LexicalDC->isFunctionOrMethod()) { 6356 unsigned IDNS = Decl::IDNS_Ordinary | Decl::IDNS_OrdinaryFriend; 6357 auto FoundDecls = Importer.findDeclsInToCtx(DC, Name); 6358 for (auto *FoundDecl : FoundDecls) { 6359 if (!FoundDecl->isInIdentifierNamespace(IDNS)) 6360 continue; 6361 6362 if (auto *FoundTemplate = dyn_cast<FunctionTemplateDecl>(FoundDecl)) { 6363 if (!hasSameVisibilityContextAndLinkage(FoundTemplate, D)) 6364 continue; 6365 if (IsStructuralMatch(D, FoundTemplate)) { 6366 FunctionTemplateDecl *TemplateWithDef = 6367 getTemplateDefinition(FoundTemplate); 6368 if (D->isThisDeclarationADefinition() && TemplateWithDef) 6369 return Importer.MapImported(D, TemplateWithDef); 6370 6371 FoundByLookup = FoundTemplate; 6372 break; 6373 // TODO: handle conflicting names 6374 } 6375 } 6376 } 6377 } 6378 6379 auto ParamsOrErr = import(D->getTemplateParameters()); 6380 if (!ParamsOrErr) 6381 return ParamsOrErr.takeError(); 6382 TemplateParameterList *Params = *ParamsOrErr; 6383 6384 FunctionDecl *TemplatedFD; 6385 if (Error Err = importInto(TemplatedFD, D->getTemplatedDecl())) 6386 return std::move(Err); 6387 6388 // At creation of the template the template parameters are "adopted" 6389 // (DeclContext is changed). After this possible change the lookup table 6390 // must be updated. 6391 // At deduction guides the DeclContext of the template parameters may be 6392 // different from what we would expect, it may be the class template, or a 6393 // probably different CXXDeductionGuideDecl. This may come from the fact that 6394 // the template parameter objects may be shared between deduction guides or 6395 // the class template, and at creation of multiple FunctionTemplateDecl 6396 // objects (for deduction guides) the same parameters are re-used. The 6397 // "adoption" happens multiple times with different parent, even recursively 6398 // for TemplateTemplateParmDecl. The same happens at import when the 6399 // FunctionTemplateDecl objects are created, but in different order. 6400 // In this way the DeclContext of these template parameters is not necessarily 6401 // the same as in the "from" context. 6402 SmallVector<DeclContext *, 2> OldParamDC; 6403 OldParamDC.reserve(Params->size()); 6404 llvm::transform(*Params, std::back_inserter(OldParamDC), 6405 [](NamedDecl *ND) { return ND->getDeclContext(); }); 6406 6407 FunctionTemplateDecl *ToFunc; 6408 if (GetImportedOrCreateDecl(ToFunc, D, Importer.getToContext(), DC, Loc, Name, 6409 Params, TemplatedFD)) 6410 return ToFunc; 6411 6412 TemplatedFD->setDescribedFunctionTemplate(ToFunc); 6413 6414 ToFunc->setAccess(D->getAccess()); 6415 ToFunc->setLexicalDeclContext(LexicalDC); 6416 LexicalDC->addDeclInternal(ToFunc); 6417 6418 ASTImporterLookupTable *LT = Importer.SharedState->getLookupTable(); 6419 if (LT && !OldParamDC.empty()) { 6420 for (unsigned int I = 0; I < OldParamDC.size(); ++I) 6421 LT->updateForced(Params->getParam(I), OldParamDC[I]); 6422 } 6423 6424 if (FoundByLookup) { 6425 auto *Recent = 6426 const_cast<FunctionTemplateDecl *>(FoundByLookup->getMostRecentDecl()); 6427 if (!TemplatedFD->getPreviousDecl()) { 6428 assert(FoundByLookup->getTemplatedDecl() && 6429 "Found decl must have its templated decl set"); 6430 auto *PrevTemplated = 6431 FoundByLookup->getTemplatedDecl()->getMostRecentDecl(); 6432 if (TemplatedFD != PrevTemplated) 6433 TemplatedFD->setPreviousDecl(PrevTemplated); 6434 } 6435 ToFunc->setPreviousDecl(Recent); 6436 } 6437 6438 return ToFunc; 6439 } 6440 6441 //---------------------------------------------------------------------------- 6442 // Import Statements 6443 //---------------------------------------------------------------------------- 6444 6445 ExpectedStmt ASTNodeImporter::VisitStmt(Stmt *S) { 6446 Importer.FromDiag(S->getBeginLoc(), diag::err_unsupported_ast_node) 6447 << S->getStmtClassName(); 6448 return make_error<ASTImportError>(ASTImportError::UnsupportedConstruct); 6449 } 6450 6451 6452 ExpectedStmt ASTNodeImporter::VisitGCCAsmStmt(GCCAsmStmt *S) { 6453 if (Importer.returnWithErrorInTest()) 6454 return make_error<ASTImportError>(ASTImportError::UnsupportedConstruct); 6455 SmallVector<IdentifierInfo *, 4> Names; 6456 for (unsigned I = 0, E = S->getNumOutputs(); I != E; I++) { 6457 IdentifierInfo *ToII = Importer.Import(S->getOutputIdentifier(I)); 6458 // ToII is nullptr when no symbolic name is given for output operand 6459 // see ParseStmtAsm::ParseAsmOperandsOpt 6460 Names.push_back(ToII); 6461 } 6462 6463 for (unsigned I = 0, E = S->getNumInputs(); I != E; I++) { 6464 IdentifierInfo *ToII = Importer.Import(S->getInputIdentifier(I)); 6465 // ToII is nullptr when no symbolic name is given for input operand 6466 // see ParseStmtAsm::ParseAsmOperandsOpt 6467 Names.push_back(ToII); 6468 } 6469 6470 SmallVector<StringLiteral *, 4> Clobbers; 6471 for (unsigned I = 0, E = S->getNumClobbers(); I != E; I++) { 6472 if (auto ClobberOrErr = import(S->getClobberStringLiteral(I))) 6473 Clobbers.push_back(*ClobberOrErr); 6474 else 6475 return ClobberOrErr.takeError(); 6476 6477 } 6478 6479 SmallVector<StringLiteral *, 4> Constraints; 6480 for (unsigned I = 0, E = S->getNumOutputs(); I != E; I++) { 6481 if (auto OutputOrErr = import(S->getOutputConstraintLiteral(I))) 6482 Constraints.push_back(*OutputOrErr); 6483 else 6484 return OutputOrErr.takeError(); 6485 } 6486 6487 for (unsigned I = 0, E = S->getNumInputs(); I != E; I++) { 6488 if (auto InputOrErr = import(S->getInputConstraintLiteral(I))) 6489 Constraints.push_back(*InputOrErr); 6490 else 6491 return InputOrErr.takeError(); 6492 } 6493 6494 SmallVector<Expr *, 4> Exprs(S->getNumOutputs() + S->getNumInputs() + 6495 S->getNumLabels()); 6496 if (Error Err = ImportContainerChecked(S->outputs(), Exprs)) 6497 return std::move(Err); 6498 6499 if (Error Err = 6500 ImportArrayChecked(S->inputs(), Exprs.begin() + S->getNumOutputs())) 6501 return std::move(Err); 6502 6503 if (Error Err = ImportArrayChecked( 6504 S->labels(), Exprs.begin() + S->getNumOutputs() + S->getNumInputs())) 6505 return std::move(Err); 6506 6507 ExpectedSLoc AsmLocOrErr = import(S->getAsmLoc()); 6508 if (!AsmLocOrErr) 6509 return AsmLocOrErr.takeError(); 6510 auto AsmStrOrErr = import(S->getAsmString()); 6511 if (!AsmStrOrErr) 6512 return AsmStrOrErr.takeError(); 6513 ExpectedSLoc RParenLocOrErr = import(S->getRParenLoc()); 6514 if (!RParenLocOrErr) 6515 return RParenLocOrErr.takeError(); 6516 6517 return new (Importer.getToContext()) GCCAsmStmt( 6518 Importer.getToContext(), 6519 *AsmLocOrErr, 6520 S->isSimple(), 6521 S->isVolatile(), 6522 S->getNumOutputs(), 6523 S->getNumInputs(), 6524 Names.data(), 6525 Constraints.data(), 6526 Exprs.data(), 6527 *AsmStrOrErr, 6528 S->getNumClobbers(), 6529 Clobbers.data(), 6530 S->getNumLabels(), 6531 *RParenLocOrErr); 6532 } 6533 6534 ExpectedStmt ASTNodeImporter::VisitDeclStmt(DeclStmt *S) { 6535 6536 Error Err = Error::success(); 6537 auto ToDG = importChecked(Err, S->getDeclGroup()); 6538 auto ToBeginLoc = importChecked(Err, S->getBeginLoc()); 6539 auto ToEndLoc = importChecked(Err, S->getEndLoc()); 6540 if (Err) 6541 return std::move(Err); 6542 return new (Importer.getToContext()) DeclStmt(ToDG, ToBeginLoc, ToEndLoc); 6543 } 6544 6545 ExpectedStmt ASTNodeImporter::VisitNullStmt(NullStmt *S) { 6546 ExpectedSLoc ToSemiLocOrErr = import(S->getSemiLoc()); 6547 if (!ToSemiLocOrErr) 6548 return ToSemiLocOrErr.takeError(); 6549 return new (Importer.getToContext()) NullStmt( 6550 *ToSemiLocOrErr, S->hasLeadingEmptyMacro()); 6551 } 6552 6553 ExpectedStmt ASTNodeImporter::VisitCompoundStmt(CompoundStmt *S) { 6554 SmallVector<Stmt *, 8> ToStmts(S->size()); 6555 6556 if (Error Err = ImportContainerChecked(S->body(), ToStmts)) 6557 return std::move(Err); 6558 6559 ExpectedSLoc ToLBracLocOrErr = import(S->getLBracLoc()); 6560 if (!ToLBracLocOrErr) 6561 return ToLBracLocOrErr.takeError(); 6562 6563 ExpectedSLoc ToRBracLocOrErr = import(S->getRBracLoc()); 6564 if (!ToRBracLocOrErr) 6565 return ToRBracLocOrErr.takeError(); 6566 6567 FPOptionsOverride FPO = 6568 S->hasStoredFPFeatures() ? S->getStoredFPFeatures() : FPOptionsOverride(); 6569 return CompoundStmt::Create(Importer.getToContext(), ToStmts, FPO, 6570 *ToLBracLocOrErr, *ToRBracLocOrErr); 6571 } 6572 6573 ExpectedStmt ASTNodeImporter::VisitCaseStmt(CaseStmt *S) { 6574 6575 Error Err = Error::success(); 6576 auto ToLHS = importChecked(Err, S->getLHS()); 6577 auto ToRHS = importChecked(Err, S->getRHS()); 6578 auto ToSubStmt = importChecked(Err, S->getSubStmt()); 6579 auto ToCaseLoc = importChecked(Err, S->getCaseLoc()); 6580 auto ToEllipsisLoc = importChecked(Err, S->getEllipsisLoc()); 6581 auto ToColonLoc = importChecked(Err, S->getColonLoc()); 6582 if (Err) 6583 return std::move(Err); 6584 6585 auto *ToStmt = CaseStmt::Create(Importer.getToContext(), ToLHS, ToRHS, 6586 ToCaseLoc, ToEllipsisLoc, ToColonLoc); 6587 ToStmt->setSubStmt(ToSubStmt); 6588 6589 return ToStmt; 6590 } 6591 6592 ExpectedStmt ASTNodeImporter::VisitDefaultStmt(DefaultStmt *S) { 6593 6594 Error Err = Error::success(); 6595 auto ToDefaultLoc = importChecked(Err, S->getDefaultLoc()); 6596 auto ToColonLoc = importChecked(Err, S->getColonLoc()); 6597 auto ToSubStmt = importChecked(Err, S->getSubStmt()); 6598 if (Err) 6599 return std::move(Err); 6600 6601 return new (Importer.getToContext()) DefaultStmt( 6602 ToDefaultLoc, ToColonLoc, ToSubStmt); 6603 } 6604 6605 ExpectedStmt ASTNodeImporter::VisitLabelStmt(LabelStmt *S) { 6606 6607 Error Err = Error::success(); 6608 auto ToIdentLoc = importChecked(Err, S->getIdentLoc()); 6609 auto ToLabelDecl = importChecked(Err, S->getDecl()); 6610 auto ToSubStmt = importChecked(Err, S->getSubStmt()); 6611 if (Err) 6612 return std::move(Err); 6613 6614 return new (Importer.getToContext()) LabelStmt( 6615 ToIdentLoc, ToLabelDecl, ToSubStmt); 6616 } 6617 6618 ExpectedStmt ASTNodeImporter::VisitAttributedStmt(AttributedStmt *S) { 6619 ExpectedSLoc ToAttrLocOrErr = import(S->getAttrLoc()); 6620 if (!ToAttrLocOrErr) 6621 return ToAttrLocOrErr.takeError(); 6622 ArrayRef<const Attr*> FromAttrs(S->getAttrs()); 6623 SmallVector<const Attr *, 1> ToAttrs(FromAttrs.size()); 6624 if (Error Err = ImportContainerChecked(FromAttrs, ToAttrs)) 6625 return std::move(Err); 6626 ExpectedStmt ToSubStmtOrErr = import(S->getSubStmt()); 6627 if (!ToSubStmtOrErr) 6628 return ToSubStmtOrErr.takeError(); 6629 6630 return AttributedStmt::Create( 6631 Importer.getToContext(), *ToAttrLocOrErr, ToAttrs, *ToSubStmtOrErr); 6632 } 6633 6634 ExpectedStmt ASTNodeImporter::VisitIfStmt(IfStmt *S) { 6635 6636 Error Err = Error::success(); 6637 auto ToIfLoc = importChecked(Err, S->getIfLoc()); 6638 auto ToInit = importChecked(Err, S->getInit()); 6639 auto ToConditionVariable = importChecked(Err, S->getConditionVariable()); 6640 auto ToCond = importChecked(Err, S->getCond()); 6641 auto ToLParenLoc = importChecked(Err, S->getLParenLoc()); 6642 auto ToRParenLoc = importChecked(Err, S->getRParenLoc()); 6643 auto ToThen = importChecked(Err, S->getThen()); 6644 auto ToElseLoc = importChecked(Err, S->getElseLoc()); 6645 auto ToElse = importChecked(Err, S->getElse()); 6646 if (Err) 6647 return std::move(Err); 6648 6649 return IfStmt::Create(Importer.getToContext(), ToIfLoc, S->getStatementKind(), 6650 ToInit, ToConditionVariable, ToCond, ToLParenLoc, 6651 ToRParenLoc, ToThen, ToElseLoc, ToElse); 6652 } 6653 6654 ExpectedStmt ASTNodeImporter::VisitSwitchStmt(SwitchStmt *S) { 6655 6656 Error Err = Error::success(); 6657 auto ToInit = importChecked(Err, S->getInit()); 6658 auto ToConditionVariable = importChecked(Err, S->getConditionVariable()); 6659 auto ToCond = importChecked(Err, S->getCond()); 6660 auto ToLParenLoc = importChecked(Err, S->getLParenLoc()); 6661 auto ToRParenLoc = importChecked(Err, S->getRParenLoc()); 6662 auto ToBody = importChecked(Err, S->getBody()); 6663 auto ToSwitchLoc = importChecked(Err, S->getSwitchLoc()); 6664 if (Err) 6665 return std::move(Err); 6666 6667 auto *ToStmt = 6668 SwitchStmt::Create(Importer.getToContext(), ToInit, ToConditionVariable, 6669 ToCond, ToLParenLoc, ToRParenLoc); 6670 ToStmt->setBody(ToBody); 6671 ToStmt->setSwitchLoc(ToSwitchLoc); 6672 6673 // Now we have to re-chain the cases. 6674 SwitchCase *LastChainedSwitchCase = nullptr; 6675 for (SwitchCase *SC = S->getSwitchCaseList(); SC != nullptr; 6676 SC = SC->getNextSwitchCase()) { 6677 Expected<SwitchCase *> ToSCOrErr = import(SC); 6678 if (!ToSCOrErr) 6679 return ToSCOrErr.takeError(); 6680 if (LastChainedSwitchCase) 6681 LastChainedSwitchCase->setNextSwitchCase(*ToSCOrErr); 6682 else 6683 ToStmt->setSwitchCaseList(*ToSCOrErr); 6684 LastChainedSwitchCase = *ToSCOrErr; 6685 } 6686 6687 return ToStmt; 6688 } 6689 6690 ExpectedStmt ASTNodeImporter::VisitWhileStmt(WhileStmt *S) { 6691 6692 Error Err = Error::success(); 6693 auto ToConditionVariable = importChecked(Err, S->getConditionVariable()); 6694 auto ToCond = importChecked(Err, S->getCond()); 6695 auto ToBody = importChecked(Err, S->getBody()); 6696 auto ToWhileLoc = importChecked(Err, S->getWhileLoc()); 6697 auto ToLParenLoc = importChecked(Err, S->getLParenLoc()); 6698 auto ToRParenLoc = importChecked(Err, S->getRParenLoc()); 6699 if (Err) 6700 return std::move(Err); 6701 6702 return WhileStmt::Create(Importer.getToContext(), ToConditionVariable, ToCond, 6703 ToBody, ToWhileLoc, ToLParenLoc, ToRParenLoc); 6704 } 6705 6706 ExpectedStmt ASTNodeImporter::VisitDoStmt(DoStmt *S) { 6707 6708 Error Err = Error::success(); 6709 auto ToBody = importChecked(Err, S->getBody()); 6710 auto ToCond = importChecked(Err, S->getCond()); 6711 auto ToDoLoc = importChecked(Err, S->getDoLoc()); 6712 auto ToWhileLoc = importChecked(Err, S->getWhileLoc()); 6713 auto ToRParenLoc = importChecked(Err, S->getRParenLoc()); 6714 if (Err) 6715 return std::move(Err); 6716 6717 return new (Importer.getToContext()) DoStmt( 6718 ToBody, ToCond, ToDoLoc, ToWhileLoc, ToRParenLoc); 6719 } 6720 6721 ExpectedStmt ASTNodeImporter::VisitForStmt(ForStmt *S) { 6722 6723 Error Err = Error::success(); 6724 auto ToInit = importChecked(Err, S->getInit()); 6725 auto ToCond = importChecked(Err, S->getCond()); 6726 auto ToConditionVariable = importChecked(Err, S->getConditionVariable()); 6727 auto ToInc = importChecked(Err, S->getInc()); 6728 auto ToBody = importChecked(Err, S->getBody()); 6729 auto ToForLoc = importChecked(Err, S->getForLoc()); 6730 auto ToLParenLoc = importChecked(Err, S->getLParenLoc()); 6731 auto ToRParenLoc = importChecked(Err, S->getRParenLoc()); 6732 if (Err) 6733 return std::move(Err); 6734 6735 return new (Importer.getToContext()) ForStmt( 6736 Importer.getToContext(), 6737 ToInit, ToCond, ToConditionVariable, ToInc, ToBody, ToForLoc, ToLParenLoc, 6738 ToRParenLoc); 6739 } 6740 6741 ExpectedStmt ASTNodeImporter::VisitGotoStmt(GotoStmt *S) { 6742 6743 Error Err = Error::success(); 6744 auto ToLabel = importChecked(Err, S->getLabel()); 6745 auto ToGotoLoc = importChecked(Err, S->getGotoLoc()); 6746 auto ToLabelLoc = importChecked(Err, S->getLabelLoc()); 6747 if (Err) 6748 return std::move(Err); 6749 6750 return new (Importer.getToContext()) GotoStmt( 6751 ToLabel, ToGotoLoc, ToLabelLoc); 6752 } 6753 6754 ExpectedStmt ASTNodeImporter::VisitIndirectGotoStmt(IndirectGotoStmt *S) { 6755 6756 Error Err = Error::success(); 6757 auto ToGotoLoc = importChecked(Err, S->getGotoLoc()); 6758 auto ToStarLoc = importChecked(Err, S->getStarLoc()); 6759 auto ToTarget = importChecked(Err, S->getTarget()); 6760 if (Err) 6761 return std::move(Err); 6762 6763 return new (Importer.getToContext()) IndirectGotoStmt( 6764 ToGotoLoc, ToStarLoc, ToTarget); 6765 } 6766 6767 ExpectedStmt ASTNodeImporter::VisitContinueStmt(ContinueStmt *S) { 6768 ExpectedSLoc ToContinueLocOrErr = import(S->getContinueLoc()); 6769 if (!ToContinueLocOrErr) 6770 return ToContinueLocOrErr.takeError(); 6771 return new (Importer.getToContext()) ContinueStmt(*ToContinueLocOrErr); 6772 } 6773 6774 ExpectedStmt ASTNodeImporter::VisitBreakStmt(BreakStmt *S) { 6775 auto ToBreakLocOrErr = import(S->getBreakLoc()); 6776 if (!ToBreakLocOrErr) 6777 return ToBreakLocOrErr.takeError(); 6778 return new (Importer.getToContext()) BreakStmt(*ToBreakLocOrErr); 6779 } 6780 6781 ExpectedStmt ASTNodeImporter::VisitReturnStmt(ReturnStmt *S) { 6782 6783 Error Err = Error::success(); 6784 auto ToReturnLoc = importChecked(Err, S->getReturnLoc()); 6785 auto ToRetValue = importChecked(Err, S->getRetValue()); 6786 auto ToNRVOCandidate = importChecked(Err, S->getNRVOCandidate()); 6787 if (Err) 6788 return std::move(Err); 6789 6790 return ReturnStmt::Create(Importer.getToContext(), ToReturnLoc, ToRetValue, 6791 ToNRVOCandidate); 6792 } 6793 6794 ExpectedStmt ASTNodeImporter::VisitCXXCatchStmt(CXXCatchStmt *S) { 6795 6796 Error Err = Error::success(); 6797 auto ToCatchLoc = importChecked(Err, S->getCatchLoc()); 6798 auto ToExceptionDecl = importChecked(Err, S->getExceptionDecl()); 6799 auto ToHandlerBlock = importChecked(Err, S->getHandlerBlock()); 6800 if (Err) 6801 return std::move(Err); 6802 6803 return new (Importer.getToContext()) CXXCatchStmt ( 6804 ToCatchLoc, ToExceptionDecl, ToHandlerBlock); 6805 } 6806 6807 ExpectedStmt ASTNodeImporter::VisitCXXTryStmt(CXXTryStmt *S) { 6808 ExpectedSLoc ToTryLocOrErr = import(S->getTryLoc()); 6809 if (!ToTryLocOrErr) 6810 return ToTryLocOrErr.takeError(); 6811 6812 ExpectedStmt ToTryBlockOrErr = import(S->getTryBlock()); 6813 if (!ToTryBlockOrErr) 6814 return ToTryBlockOrErr.takeError(); 6815 6816 SmallVector<Stmt *, 1> ToHandlers(S->getNumHandlers()); 6817 for (unsigned HI = 0, HE = S->getNumHandlers(); HI != HE; ++HI) { 6818 CXXCatchStmt *FromHandler = S->getHandler(HI); 6819 if (auto ToHandlerOrErr = import(FromHandler)) 6820 ToHandlers[HI] = *ToHandlerOrErr; 6821 else 6822 return ToHandlerOrErr.takeError(); 6823 } 6824 6825 return CXXTryStmt::Create(Importer.getToContext(), *ToTryLocOrErr, 6826 cast<CompoundStmt>(*ToTryBlockOrErr), ToHandlers); 6827 } 6828 6829 ExpectedStmt ASTNodeImporter::VisitCXXForRangeStmt(CXXForRangeStmt *S) { 6830 6831 Error Err = Error::success(); 6832 auto ToInit = importChecked(Err, S->getInit()); 6833 auto ToRangeStmt = importChecked(Err, S->getRangeStmt()); 6834 auto ToBeginStmt = importChecked(Err, S->getBeginStmt()); 6835 auto ToEndStmt = importChecked(Err, S->getEndStmt()); 6836 auto ToCond = importChecked(Err, S->getCond()); 6837 auto ToInc = importChecked(Err, S->getInc()); 6838 auto ToLoopVarStmt = importChecked(Err, S->getLoopVarStmt()); 6839 auto ToBody = importChecked(Err, S->getBody()); 6840 auto ToForLoc = importChecked(Err, S->getForLoc()); 6841 auto ToCoawaitLoc = importChecked(Err, S->getCoawaitLoc()); 6842 auto ToColonLoc = importChecked(Err, S->getColonLoc()); 6843 auto ToRParenLoc = importChecked(Err, S->getRParenLoc()); 6844 if (Err) 6845 return std::move(Err); 6846 6847 return new (Importer.getToContext()) CXXForRangeStmt( 6848 ToInit, ToRangeStmt, ToBeginStmt, ToEndStmt, ToCond, ToInc, ToLoopVarStmt, 6849 ToBody, ToForLoc, ToCoawaitLoc, ToColonLoc, ToRParenLoc); 6850 } 6851 6852 ExpectedStmt 6853 ASTNodeImporter::VisitObjCForCollectionStmt(ObjCForCollectionStmt *S) { 6854 Error Err = Error::success(); 6855 auto ToElement = importChecked(Err, S->getElement()); 6856 auto ToCollection = importChecked(Err, S->getCollection()); 6857 auto ToBody = importChecked(Err, S->getBody()); 6858 auto ToForLoc = importChecked(Err, S->getForLoc()); 6859 auto ToRParenLoc = importChecked(Err, S->getRParenLoc()); 6860 if (Err) 6861 return std::move(Err); 6862 6863 return new (Importer.getToContext()) ObjCForCollectionStmt(ToElement, 6864 ToCollection, 6865 ToBody, 6866 ToForLoc, 6867 ToRParenLoc); 6868 } 6869 6870 ExpectedStmt ASTNodeImporter::VisitObjCAtCatchStmt(ObjCAtCatchStmt *S) { 6871 6872 Error Err = Error::success(); 6873 auto ToAtCatchLoc = importChecked(Err, S->getAtCatchLoc()); 6874 auto ToRParenLoc = importChecked(Err, S->getRParenLoc()); 6875 auto ToCatchParamDecl = importChecked(Err, S->getCatchParamDecl()); 6876 auto ToCatchBody = importChecked(Err, S->getCatchBody()); 6877 if (Err) 6878 return std::move(Err); 6879 6880 return new (Importer.getToContext()) ObjCAtCatchStmt ( 6881 ToAtCatchLoc, ToRParenLoc, ToCatchParamDecl, ToCatchBody); 6882 } 6883 6884 ExpectedStmt ASTNodeImporter::VisitObjCAtFinallyStmt(ObjCAtFinallyStmt *S) { 6885 ExpectedSLoc ToAtFinallyLocOrErr = import(S->getAtFinallyLoc()); 6886 if (!ToAtFinallyLocOrErr) 6887 return ToAtFinallyLocOrErr.takeError(); 6888 ExpectedStmt ToAtFinallyStmtOrErr = import(S->getFinallyBody()); 6889 if (!ToAtFinallyStmtOrErr) 6890 return ToAtFinallyStmtOrErr.takeError(); 6891 return new (Importer.getToContext()) ObjCAtFinallyStmt(*ToAtFinallyLocOrErr, 6892 *ToAtFinallyStmtOrErr); 6893 } 6894 6895 ExpectedStmt ASTNodeImporter::VisitObjCAtTryStmt(ObjCAtTryStmt *S) { 6896 6897 Error Err = Error::success(); 6898 auto ToAtTryLoc = importChecked(Err, S->getAtTryLoc()); 6899 auto ToTryBody = importChecked(Err, S->getTryBody()); 6900 auto ToFinallyStmt = importChecked(Err, S->getFinallyStmt()); 6901 if (Err) 6902 return std::move(Err); 6903 6904 SmallVector<Stmt *, 1> ToCatchStmts(S->getNumCatchStmts()); 6905 for (unsigned CI = 0, CE = S->getNumCatchStmts(); CI != CE; ++CI) { 6906 ObjCAtCatchStmt *FromCatchStmt = S->getCatchStmt(CI); 6907 if (ExpectedStmt ToCatchStmtOrErr = import(FromCatchStmt)) 6908 ToCatchStmts[CI] = *ToCatchStmtOrErr; 6909 else 6910 return ToCatchStmtOrErr.takeError(); 6911 } 6912 6913 return ObjCAtTryStmt::Create(Importer.getToContext(), 6914 ToAtTryLoc, ToTryBody, 6915 ToCatchStmts.begin(), ToCatchStmts.size(), 6916 ToFinallyStmt); 6917 } 6918 6919 ExpectedStmt 6920 ASTNodeImporter::VisitObjCAtSynchronizedStmt(ObjCAtSynchronizedStmt *S) { 6921 6922 Error Err = Error::success(); 6923 auto ToAtSynchronizedLoc = importChecked(Err, S->getAtSynchronizedLoc()); 6924 auto ToSynchExpr = importChecked(Err, S->getSynchExpr()); 6925 auto ToSynchBody = importChecked(Err, S->getSynchBody()); 6926 if (Err) 6927 return std::move(Err); 6928 6929 return new (Importer.getToContext()) ObjCAtSynchronizedStmt( 6930 ToAtSynchronizedLoc, ToSynchExpr, ToSynchBody); 6931 } 6932 6933 ExpectedStmt ASTNodeImporter::VisitObjCAtThrowStmt(ObjCAtThrowStmt *S) { 6934 ExpectedSLoc ToThrowLocOrErr = import(S->getThrowLoc()); 6935 if (!ToThrowLocOrErr) 6936 return ToThrowLocOrErr.takeError(); 6937 ExpectedExpr ToThrowExprOrErr = import(S->getThrowExpr()); 6938 if (!ToThrowExprOrErr) 6939 return ToThrowExprOrErr.takeError(); 6940 return new (Importer.getToContext()) ObjCAtThrowStmt( 6941 *ToThrowLocOrErr, *ToThrowExprOrErr); 6942 } 6943 6944 ExpectedStmt ASTNodeImporter::VisitObjCAutoreleasePoolStmt( 6945 ObjCAutoreleasePoolStmt *S) { 6946 ExpectedSLoc ToAtLocOrErr = import(S->getAtLoc()); 6947 if (!ToAtLocOrErr) 6948 return ToAtLocOrErr.takeError(); 6949 ExpectedStmt ToSubStmtOrErr = import(S->getSubStmt()); 6950 if (!ToSubStmtOrErr) 6951 return ToSubStmtOrErr.takeError(); 6952 return new (Importer.getToContext()) ObjCAutoreleasePoolStmt(*ToAtLocOrErr, 6953 *ToSubStmtOrErr); 6954 } 6955 6956 //---------------------------------------------------------------------------- 6957 // Import Expressions 6958 //---------------------------------------------------------------------------- 6959 ExpectedStmt ASTNodeImporter::VisitExpr(Expr *E) { 6960 Importer.FromDiag(E->getBeginLoc(), diag::err_unsupported_ast_node) 6961 << E->getStmtClassName(); 6962 return make_error<ASTImportError>(ASTImportError::UnsupportedConstruct); 6963 } 6964 6965 ExpectedStmt ASTNodeImporter::VisitSourceLocExpr(SourceLocExpr *E) { 6966 Error Err = Error::success(); 6967 auto ToType = importChecked(Err, E->getType()); 6968 auto BLoc = importChecked(Err, E->getBeginLoc()); 6969 auto RParenLoc = importChecked(Err, E->getEndLoc()); 6970 if (Err) 6971 return std::move(Err); 6972 auto ParentContextOrErr = Importer.ImportContext(E->getParentContext()); 6973 if (!ParentContextOrErr) 6974 return ParentContextOrErr.takeError(); 6975 6976 return new (Importer.getToContext()) 6977 SourceLocExpr(Importer.getToContext(), E->getIdentKind(), ToType, BLoc, 6978 RParenLoc, *ParentContextOrErr); 6979 } 6980 6981 ExpectedStmt ASTNodeImporter::VisitVAArgExpr(VAArgExpr *E) { 6982 6983 Error Err = Error::success(); 6984 auto ToBuiltinLoc = importChecked(Err, E->getBuiltinLoc()); 6985 auto ToSubExpr = importChecked(Err, E->getSubExpr()); 6986 auto ToWrittenTypeInfo = importChecked(Err, E->getWrittenTypeInfo()); 6987 auto ToRParenLoc = importChecked(Err, E->getRParenLoc()); 6988 auto ToType = importChecked(Err, E->getType()); 6989 if (Err) 6990 return std::move(Err); 6991 6992 return new (Importer.getToContext()) VAArgExpr( 6993 ToBuiltinLoc, ToSubExpr, ToWrittenTypeInfo, ToRParenLoc, ToType, 6994 E->isMicrosoftABI()); 6995 } 6996 6997 ExpectedStmt ASTNodeImporter::VisitChooseExpr(ChooseExpr *E) { 6998 6999 Error Err = Error::success(); 7000 auto ToCond = importChecked(Err, E->getCond()); 7001 auto ToLHS = importChecked(Err, E->getLHS()); 7002 auto ToRHS = importChecked(Err, E->getRHS()); 7003 auto ToBuiltinLoc = importChecked(Err, E->getBuiltinLoc()); 7004 auto ToRParenLoc = importChecked(Err, E->getRParenLoc()); 7005 auto ToType = importChecked(Err, E->getType()); 7006 if (Err) 7007 return std::move(Err); 7008 7009 ExprValueKind VK = E->getValueKind(); 7010 ExprObjectKind OK = E->getObjectKind(); 7011 7012 // The value of CondIsTrue only matters if the value is not 7013 // condition-dependent. 7014 bool CondIsTrue = !E->isConditionDependent() && E->isConditionTrue(); 7015 7016 return new (Importer.getToContext()) 7017 ChooseExpr(ToBuiltinLoc, ToCond, ToLHS, ToRHS, ToType, VK, OK, 7018 ToRParenLoc, CondIsTrue); 7019 } 7020 7021 ExpectedStmt ASTNodeImporter::VisitShuffleVectorExpr(ShuffleVectorExpr *E) { 7022 Error Err = Error::success(); 7023 auto ToRParenLoc = importChecked(Err, E->getRParenLoc()); 7024 auto ToBeginLoc = importChecked(Err, E->getBeginLoc()); 7025 auto ToType = importChecked(Err, E->getType()); 7026 const unsigned NumSubExprs = E->getNumSubExprs(); 7027 7028 llvm::SmallVector<Expr *, 8> ToSubExprs; 7029 llvm::ArrayRef<Expr *> FromSubExprs(E->getSubExprs(), NumSubExprs); 7030 ToSubExprs.resize(NumSubExprs); 7031 7032 if ((Err = ImportContainerChecked(FromSubExprs, ToSubExprs))) 7033 return std::move(Err); 7034 7035 return new (Importer.getToContext()) ShuffleVectorExpr( 7036 Importer.getToContext(), ToSubExprs, ToType, ToBeginLoc, ToRParenLoc); 7037 } 7038 7039 ExpectedStmt ASTNodeImporter::VisitGNUNullExpr(GNUNullExpr *E) { 7040 ExpectedType TypeOrErr = import(E->getType()); 7041 if (!TypeOrErr) 7042 return TypeOrErr.takeError(); 7043 7044 ExpectedSLoc BeginLocOrErr = import(E->getBeginLoc()); 7045 if (!BeginLocOrErr) 7046 return BeginLocOrErr.takeError(); 7047 7048 return new (Importer.getToContext()) GNUNullExpr(*TypeOrErr, *BeginLocOrErr); 7049 } 7050 7051 ExpectedStmt 7052 ASTNodeImporter::VisitGenericSelectionExpr(GenericSelectionExpr *E) { 7053 Error Err = Error::success(); 7054 auto ToGenericLoc = importChecked(Err, E->getGenericLoc()); 7055 Expr *ToControllingExpr = nullptr; 7056 TypeSourceInfo *ToControllingType = nullptr; 7057 if (E->isExprPredicate()) 7058 ToControllingExpr = importChecked(Err, E->getControllingExpr()); 7059 else 7060 ToControllingType = importChecked(Err, E->getControllingType()); 7061 assert((ToControllingExpr || ToControllingType) && 7062 "Either the controlling expr or type must be nonnull"); 7063 auto ToDefaultLoc = importChecked(Err, E->getDefaultLoc()); 7064 auto ToRParenLoc = importChecked(Err, E->getRParenLoc()); 7065 if (Err) 7066 return std::move(Err); 7067 7068 ArrayRef<const TypeSourceInfo *> FromAssocTypes(E->getAssocTypeSourceInfos()); 7069 SmallVector<TypeSourceInfo *, 1> ToAssocTypes(FromAssocTypes.size()); 7070 if (Error Err = ImportContainerChecked(FromAssocTypes, ToAssocTypes)) 7071 return std::move(Err); 7072 7073 ArrayRef<const Expr *> FromAssocExprs(E->getAssocExprs()); 7074 SmallVector<Expr *, 1> ToAssocExprs(FromAssocExprs.size()); 7075 if (Error Err = ImportContainerChecked(FromAssocExprs, ToAssocExprs)) 7076 return std::move(Err); 7077 7078 const ASTContext &ToCtx = Importer.getToContext(); 7079 if (E->isResultDependent()) { 7080 if (ToControllingExpr) { 7081 return GenericSelectionExpr::Create( 7082 ToCtx, ToGenericLoc, ToControllingExpr, llvm::ArrayRef(ToAssocTypes), 7083 llvm::ArrayRef(ToAssocExprs), ToDefaultLoc, ToRParenLoc, 7084 E->containsUnexpandedParameterPack()); 7085 } 7086 return GenericSelectionExpr::Create( 7087 ToCtx, ToGenericLoc, ToControllingType, llvm::ArrayRef(ToAssocTypes), 7088 llvm::ArrayRef(ToAssocExprs), ToDefaultLoc, ToRParenLoc, 7089 E->containsUnexpandedParameterPack()); 7090 } 7091 7092 if (ToControllingExpr) { 7093 return GenericSelectionExpr::Create( 7094 ToCtx, ToGenericLoc, ToControllingExpr, llvm::ArrayRef(ToAssocTypes), 7095 llvm::ArrayRef(ToAssocExprs), ToDefaultLoc, ToRParenLoc, 7096 E->containsUnexpandedParameterPack(), E->getResultIndex()); 7097 } 7098 return GenericSelectionExpr::Create( 7099 ToCtx, ToGenericLoc, ToControllingType, llvm::ArrayRef(ToAssocTypes), 7100 llvm::ArrayRef(ToAssocExprs), ToDefaultLoc, ToRParenLoc, 7101 E->containsUnexpandedParameterPack(), E->getResultIndex()); 7102 } 7103 7104 ExpectedStmt ASTNodeImporter::VisitPredefinedExpr(PredefinedExpr *E) { 7105 7106 Error Err = Error::success(); 7107 auto ToBeginLoc = importChecked(Err, E->getBeginLoc()); 7108 auto ToType = importChecked(Err, E->getType()); 7109 auto ToFunctionName = importChecked(Err, E->getFunctionName()); 7110 if (Err) 7111 return std::move(Err); 7112 7113 return PredefinedExpr::Create(Importer.getToContext(), ToBeginLoc, ToType, 7114 E->getIdentKind(), E->isTransparent(), 7115 ToFunctionName); 7116 } 7117 7118 ExpectedStmt ASTNodeImporter::VisitDeclRefExpr(DeclRefExpr *E) { 7119 7120 Error Err = Error::success(); 7121 auto ToQualifierLoc = importChecked(Err, E->getQualifierLoc()); 7122 auto ToTemplateKeywordLoc = importChecked(Err, E->getTemplateKeywordLoc()); 7123 auto ToDecl = importChecked(Err, E->getDecl()); 7124 auto ToLocation = importChecked(Err, E->getLocation()); 7125 auto ToType = importChecked(Err, E->getType()); 7126 if (Err) 7127 return std::move(Err); 7128 7129 NamedDecl *ToFoundD = nullptr; 7130 if (E->getDecl() != E->getFoundDecl()) { 7131 auto FoundDOrErr = import(E->getFoundDecl()); 7132 if (!FoundDOrErr) 7133 return FoundDOrErr.takeError(); 7134 ToFoundD = *FoundDOrErr; 7135 } 7136 7137 TemplateArgumentListInfo ToTAInfo; 7138 TemplateArgumentListInfo *ToResInfo = nullptr; 7139 if (E->hasExplicitTemplateArgs()) { 7140 if (Error Err = 7141 ImportTemplateArgumentListInfo(E->getLAngleLoc(), E->getRAngleLoc(), 7142 E->template_arguments(), ToTAInfo)) 7143 return std::move(Err); 7144 ToResInfo = &ToTAInfo; 7145 } 7146 7147 auto *ToE = DeclRefExpr::Create( 7148 Importer.getToContext(), ToQualifierLoc, ToTemplateKeywordLoc, ToDecl, 7149 E->refersToEnclosingVariableOrCapture(), ToLocation, ToType, 7150 E->getValueKind(), ToFoundD, ToResInfo, E->isNonOdrUse()); 7151 if (E->hadMultipleCandidates()) 7152 ToE->setHadMultipleCandidates(true); 7153 ToE->setIsImmediateEscalating(E->isImmediateEscalating()); 7154 return ToE; 7155 } 7156 7157 ExpectedStmt ASTNodeImporter::VisitImplicitValueInitExpr(ImplicitValueInitExpr *E) { 7158 ExpectedType TypeOrErr = import(E->getType()); 7159 if (!TypeOrErr) 7160 return TypeOrErr.takeError(); 7161 7162 return new (Importer.getToContext()) ImplicitValueInitExpr(*TypeOrErr); 7163 } 7164 7165 ExpectedStmt ASTNodeImporter::VisitDesignatedInitExpr(DesignatedInitExpr *E) { 7166 ExpectedExpr ToInitOrErr = import(E->getInit()); 7167 if (!ToInitOrErr) 7168 return ToInitOrErr.takeError(); 7169 7170 ExpectedSLoc ToEqualOrColonLocOrErr = import(E->getEqualOrColonLoc()); 7171 if (!ToEqualOrColonLocOrErr) 7172 return ToEqualOrColonLocOrErr.takeError(); 7173 7174 SmallVector<Expr *, 4> ToIndexExprs(E->getNumSubExprs() - 1); 7175 // List elements from the second, the first is Init itself 7176 for (unsigned I = 1, N = E->getNumSubExprs(); I < N; I++) { 7177 if (ExpectedExpr ToArgOrErr = import(E->getSubExpr(I))) 7178 ToIndexExprs[I - 1] = *ToArgOrErr; 7179 else 7180 return ToArgOrErr.takeError(); 7181 } 7182 7183 SmallVector<Designator, 4> ToDesignators(E->size()); 7184 if (Error Err = ImportContainerChecked(E->designators(), ToDesignators)) 7185 return std::move(Err); 7186 7187 return DesignatedInitExpr::Create( 7188 Importer.getToContext(), ToDesignators, 7189 ToIndexExprs, *ToEqualOrColonLocOrErr, 7190 E->usesGNUSyntax(), *ToInitOrErr); 7191 } 7192 7193 ExpectedStmt 7194 ASTNodeImporter::VisitCXXNullPtrLiteralExpr(CXXNullPtrLiteralExpr *E) { 7195 ExpectedType ToTypeOrErr = import(E->getType()); 7196 if (!ToTypeOrErr) 7197 return ToTypeOrErr.takeError(); 7198 7199 ExpectedSLoc ToLocationOrErr = import(E->getLocation()); 7200 if (!ToLocationOrErr) 7201 return ToLocationOrErr.takeError(); 7202 7203 return new (Importer.getToContext()) CXXNullPtrLiteralExpr( 7204 *ToTypeOrErr, *ToLocationOrErr); 7205 } 7206 7207 ExpectedStmt ASTNodeImporter::VisitIntegerLiteral(IntegerLiteral *E) { 7208 ExpectedType ToTypeOrErr = import(E->getType()); 7209 if (!ToTypeOrErr) 7210 return ToTypeOrErr.takeError(); 7211 7212 ExpectedSLoc ToLocationOrErr = import(E->getLocation()); 7213 if (!ToLocationOrErr) 7214 return ToLocationOrErr.takeError(); 7215 7216 return IntegerLiteral::Create( 7217 Importer.getToContext(), E->getValue(), *ToTypeOrErr, *ToLocationOrErr); 7218 } 7219 7220 7221 ExpectedStmt ASTNodeImporter::VisitFloatingLiteral(FloatingLiteral *E) { 7222 ExpectedType ToTypeOrErr = import(E->getType()); 7223 if (!ToTypeOrErr) 7224 return ToTypeOrErr.takeError(); 7225 7226 ExpectedSLoc ToLocationOrErr = import(E->getLocation()); 7227 if (!ToLocationOrErr) 7228 return ToLocationOrErr.takeError(); 7229 7230 return FloatingLiteral::Create( 7231 Importer.getToContext(), E->getValue(), E->isExact(), 7232 *ToTypeOrErr, *ToLocationOrErr); 7233 } 7234 7235 ExpectedStmt ASTNodeImporter::VisitImaginaryLiteral(ImaginaryLiteral *E) { 7236 auto ToTypeOrErr = import(E->getType()); 7237 if (!ToTypeOrErr) 7238 return ToTypeOrErr.takeError(); 7239 7240 ExpectedExpr ToSubExprOrErr = import(E->getSubExpr()); 7241 if (!ToSubExprOrErr) 7242 return ToSubExprOrErr.takeError(); 7243 7244 return new (Importer.getToContext()) ImaginaryLiteral( 7245 *ToSubExprOrErr, *ToTypeOrErr); 7246 } 7247 7248 ExpectedStmt ASTNodeImporter::VisitFixedPointLiteral(FixedPointLiteral *E) { 7249 auto ToTypeOrErr = import(E->getType()); 7250 if (!ToTypeOrErr) 7251 return ToTypeOrErr.takeError(); 7252 7253 ExpectedSLoc ToLocationOrErr = import(E->getLocation()); 7254 if (!ToLocationOrErr) 7255 return ToLocationOrErr.takeError(); 7256 7257 return new (Importer.getToContext()) FixedPointLiteral( 7258 Importer.getToContext(), E->getValue(), *ToTypeOrErr, *ToLocationOrErr, 7259 Importer.getToContext().getFixedPointScale(*ToTypeOrErr)); 7260 } 7261 7262 ExpectedStmt ASTNodeImporter::VisitCharacterLiteral(CharacterLiteral *E) { 7263 ExpectedType ToTypeOrErr = import(E->getType()); 7264 if (!ToTypeOrErr) 7265 return ToTypeOrErr.takeError(); 7266 7267 ExpectedSLoc ToLocationOrErr = import(E->getLocation()); 7268 if (!ToLocationOrErr) 7269 return ToLocationOrErr.takeError(); 7270 7271 return new (Importer.getToContext()) CharacterLiteral( 7272 E->getValue(), E->getKind(), *ToTypeOrErr, *ToLocationOrErr); 7273 } 7274 7275 ExpectedStmt ASTNodeImporter::VisitStringLiteral(StringLiteral *E) { 7276 ExpectedType ToTypeOrErr = import(E->getType()); 7277 if (!ToTypeOrErr) 7278 return ToTypeOrErr.takeError(); 7279 7280 SmallVector<SourceLocation, 4> ToLocations(E->getNumConcatenated()); 7281 if (Error Err = ImportArrayChecked( 7282 E->tokloc_begin(), E->tokloc_end(), ToLocations.begin())) 7283 return std::move(Err); 7284 7285 return StringLiteral::Create( 7286 Importer.getToContext(), E->getBytes(), E->getKind(), E->isPascal(), 7287 *ToTypeOrErr, ToLocations.data(), ToLocations.size()); 7288 } 7289 7290 ExpectedStmt ASTNodeImporter::VisitCompoundLiteralExpr(CompoundLiteralExpr *E) { 7291 7292 Error Err = Error::success(); 7293 auto ToLParenLoc = importChecked(Err, E->getLParenLoc()); 7294 auto ToTypeSourceInfo = importChecked(Err, E->getTypeSourceInfo()); 7295 auto ToType = importChecked(Err, E->getType()); 7296 auto ToInitializer = importChecked(Err, E->getInitializer()); 7297 if (Err) 7298 return std::move(Err); 7299 7300 return new (Importer.getToContext()) CompoundLiteralExpr( 7301 ToLParenLoc, ToTypeSourceInfo, ToType, E->getValueKind(), 7302 ToInitializer, E->isFileScope()); 7303 } 7304 7305 ExpectedStmt ASTNodeImporter::VisitAtomicExpr(AtomicExpr *E) { 7306 7307 Error Err = Error::success(); 7308 auto ToBuiltinLoc = importChecked(Err, E->getBuiltinLoc()); 7309 auto ToType = importChecked(Err, E->getType()); 7310 auto ToRParenLoc = importChecked(Err, E->getRParenLoc()); 7311 if (Err) 7312 return std::move(Err); 7313 7314 SmallVector<Expr *, 6> ToExprs(E->getNumSubExprs()); 7315 if (Error Err = ImportArrayChecked( 7316 E->getSubExprs(), E->getSubExprs() + E->getNumSubExprs(), 7317 ToExprs.begin())) 7318 return std::move(Err); 7319 7320 return new (Importer.getToContext()) AtomicExpr( 7321 7322 ToBuiltinLoc, ToExprs, ToType, E->getOp(), ToRParenLoc); 7323 } 7324 7325 ExpectedStmt ASTNodeImporter::VisitAddrLabelExpr(AddrLabelExpr *E) { 7326 Error Err = Error::success(); 7327 auto ToAmpAmpLoc = importChecked(Err, E->getAmpAmpLoc()); 7328 auto ToLabelLoc = importChecked(Err, E->getLabelLoc()); 7329 auto ToLabel = importChecked(Err, E->getLabel()); 7330 auto ToType = importChecked(Err, E->getType()); 7331 if (Err) 7332 return std::move(Err); 7333 7334 return new (Importer.getToContext()) AddrLabelExpr( 7335 ToAmpAmpLoc, ToLabelLoc, ToLabel, ToType); 7336 } 7337 ExpectedStmt ASTNodeImporter::VisitConstantExpr(ConstantExpr *E) { 7338 Error Err = Error::success(); 7339 auto ToSubExpr = importChecked(Err, E->getSubExpr()); 7340 auto ToResult = importChecked(Err, E->getAPValueResult()); 7341 if (Err) 7342 return std::move(Err); 7343 7344 return ConstantExpr::Create(Importer.getToContext(), ToSubExpr, ToResult); 7345 } 7346 ExpectedStmt ASTNodeImporter::VisitParenExpr(ParenExpr *E) { 7347 Error Err = Error::success(); 7348 auto ToLParen = importChecked(Err, E->getLParen()); 7349 auto ToRParen = importChecked(Err, E->getRParen()); 7350 auto ToSubExpr = importChecked(Err, E->getSubExpr()); 7351 if (Err) 7352 return std::move(Err); 7353 7354 return new (Importer.getToContext()) 7355 ParenExpr(ToLParen, ToRParen, ToSubExpr); 7356 } 7357 7358 ExpectedStmt ASTNodeImporter::VisitParenListExpr(ParenListExpr *E) { 7359 SmallVector<Expr *, 4> ToExprs(E->getNumExprs()); 7360 if (Error Err = ImportContainerChecked(E->exprs(), ToExprs)) 7361 return std::move(Err); 7362 7363 ExpectedSLoc ToLParenLocOrErr = import(E->getLParenLoc()); 7364 if (!ToLParenLocOrErr) 7365 return ToLParenLocOrErr.takeError(); 7366 7367 ExpectedSLoc ToRParenLocOrErr = import(E->getRParenLoc()); 7368 if (!ToRParenLocOrErr) 7369 return ToRParenLocOrErr.takeError(); 7370 7371 return ParenListExpr::Create(Importer.getToContext(), *ToLParenLocOrErr, 7372 ToExprs, *ToRParenLocOrErr); 7373 } 7374 7375 ExpectedStmt ASTNodeImporter::VisitStmtExpr(StmtExpr *E) { 7376 Error Err = Error::success(); 7377 auto ToSubStmt = importChecked(Err, E->getSubStmt()); 7378 auto ToType = importChecked(Err, E->getType()); 7379 auto ToLParenLoc = importChecked(Err, E->getLParenLoc()); 7380 auto ToRParenLoc = importChecked(Err, E->getRParenLoc()); 7381 if (Err) 7382 return std::move(Err); 7383 7384 return new (Importer.getToContext()) 7385 StmtExpr(ToSubStmt, ToType, ToLParenLoc, ToRParenLoc, 7386 E->getTemplateDepth()); 7387 } 7388 7389 ExpectedStmt ASTNodeImporter::VisitUnaryOperator(UnaryOperator *E) { 7390 Error Err = Error::success(); 7391 auto ToSubExpr = importChecked(Err, E->getSubExpr()); 7392 auto ToType = importChecked(Err, E->getType()); 7393 auto ToOperatorLoc = importChecked(Err, E->getOperatorLoc()); 7394 if (Err) 7395 return std::move(Err); 7396 7397 return UnaryOperator::Create( 7398 Importer.getToContext(), ToSubExpr, E->getOpcode(), ToType, 7399 E->getValueKind(), E->getObjectKind(), ToOperatorLoc, E->canOverflow(), 7400 E->getFPOptionsOverride()); 7401 } 7402 7403 ExpectedStmt 7404 7405 ASTNodeImporter::VisitUnaryExprOrTypeTraitExpr(UnaryExprOrTypeTraitExpr *E) { 7406 Error Err = Error::success(); 7407 auto ToType = importChecked(Err, E->getType()); 7408 auto ToOperatorLoc = importChecked(Err, E->getOperatorLoc()); 7409 auto ToRParenLoc = importChecked(Err, E->getRParenLoc()); 7410 if (Err) 7411 return std::move(Err); 7412 7413 if (E->isArgumentType()) { 7414 Expected<TypeSourceInfo *> ToArgumentTypeInfoOrErr = 7415 import(E->getArgumentTypeInfo()); 7416 if (!ToArgumentTypeInfoOrErr) 7417 return ToArgumentTypeInfoOrErr.takeError(); 7418 7419 return new (Importer.getToContext()) UnaryExprOrTypeTraitExpr( 7420 E->getKind(), *ToArgumentTypeInfoOrErr, ToType, ToOperatorLoc, 7421 ToRParenLoc); 7422 } 7423 7424 ExpectedExpr ToArgumentExprOrErr = import(E->getArgumentExpr()); 7425 if (!ToArgumentExprOrErr) 7426 return ToArgumentExprOrErr.takeError(); 7427 7428 return new (Importer.getToContext()) UnaryExprOrTypeTraitExpr( 7429 E->getKind(), *ToArgumentExprOrErr, ToType, ToOperatorLoc, ToRParenLoc); 7430 } 7431 7432 ExpectedStmt ASTNodeImporter::VisitBinaryOperator(BinaryOperator *E) { 7433 Error Err = Error::success(); 7434 auto ToLHS = importChecked(Err, E->getLHS()); 7435 auto ToRHS = importChecked(Err, E->getRHS()); 7436 auto ToType = importChecked(Err, E->getType()); 7437 auto ToOperatorLoc = importChecked(Err, E->getOperatorLoc()); 7438 if (Err) 7439 return std::move(Err); 7440 7441 return BinaryOperator::Create( 7442 Importer.getToContext(), ToLHS, ToRHS, E->getOpcode(), ToType, 7443 E->getValueKind(), E->getObjectKind(), ToOperatorLoc, 7444 E->getFPFeatures()); 7445 } 7446 7447 ExpectedStmt ASTNodeImporter::VisitConditionalOperator(ConditionalOperator *E) { 7448 Error Err = Error::success(); 7449 auto ToCond = importChecked(Err, E->getCond()); 7450 auto ToQuestionLoc = importChecked(Err, E->getQuestionLoc()); 7451 auto ToLHS = importChecked(Err, E->getLHS()); 7452 auto ToColonLoc = importChecked(Err, E->getColonLoc()); 7453 auto ToRHS = importChecked(Err, E->getRHS()); 7454 auto ToType = importChecked(Err, E->getType()); 7455 if (Err) 7456 return std::move(Err); 7457 7458 return new (Importer.getToContext()) ConditionalOperator( 7459 ToCond, ToQuestionLoc, ToLHS, ToColonLoc, ToRHS, ToType, 7460 E->getValueKind(), E->getObjectKind()); 7461 } 7462 7463 ExpectedStmt 7464 ASTNodeImporter::VisitBinaryConditionalOperator(BinaryConditionalOperator *E) { 7465 Error Err = Error::success(); 7466 auto ToCommon = importChecked(Err, E->getCommon()); 7467 auto ToOpaqueValue = importChecked(Err, E->getOpaqueValue()); 7468 auto ToCond = importChecked(Err, E->getCond()); 7469 auto ToTrueExpr = importChecked(Err, E->getTrueExpr()); 7470 auto ToFalseExpr = importChecked(Err, E->getFalseExpr()); 7471 auto ToQuestionLoc = importChecked(Err, E->getQuestionLoc()); 7472 auto ToColonLoc = importChecked(Err, E->getColonLoc()); 7473 auto ToType = importChecked(Err, E->getType()); 7474 if (Err) 7475 return std::move(Err); 7476 7477 return new (Importer.getToContext()) BinaryConditionalOperator( 7478 ToCommon, ToOpaqueValue, ToCond, ToTrueExpr, ToFalseExpr, 7479 ToQuestionLoc, ToColonLoc, ToType, E->getValueKind(), 7480 E->getObjectKind()); 7481 } 7482 7483 ExpectedStmt ASTNodeImporter::VisitCXXRewrittenBinaryOperator( 7484 CXXRewrittenBinaryOperator *E) { 7485 Error Err = Error::success(); 7486 auto ToSemanticForm = importChecked(Err, E->getSemanticForm()); 7487 if (Err) 7488 return std::move(Err); 7489 7490 return new (Importer.getToContext()) 7491 CXXRewrittenBinaryOperator(ToSemanticForm, E->isReversed()); 7492 } 7493 7494 ExpectedStmt ASTNodeImporter::VisitArrayTypeTraitExpr(ArrayTypeTraitExpr *E) { 7495 Error Err = Error::success(); 7496 auto ToBeginLoc = importChecked(Err, E->getBeginLoc()); 7497 auto ToQueriedTypeSourceInfo = 7498 importChecked(Err, E->getQueriedTypeSourceInfo()); 7499 auto ToDimensionExpression = importChecked(Err, E->getDimensionExpression()); 7500 auto ToEndLoc = importChecked(Err, E->getEndLoc()); 7501 auto ToType = importChecked(Err, E->getType()); 7502 if (Err) 7503 return std::move(Err); 7504 7505 return new (Importer.getToContext()) ArrayTypeTraitExpr( 7506 ToBeginLoc, E->getTrait(), ToQueriedTypeSourceInfo, E->getValue(), 7507 ToDimensionExpression, ToEndLoc, ToType); 7508 } 7509 7510 ExpectedStmt ASTNodeImporter::VisitExpressionTraitExpr(ExpressionTraitExpr *E) { 7511 Error Err = Error::success(); 7512 auto ToBeginLoc = importChecked(Err, E->getBeginLoc()); 7513 auto ToQueriedExpression = importChecked(Err, E->getQueriedExpression()); 7514 auto ToEndLoc = importChecked(Err, E->getEndLoc()); 7515 auto ToType = importChecked(Err, E->getType()); 7516 if (Err) 7517 return std::move(Err); 7518 7519 return new (Importer.getToContext()) ExpressionTraitExpr( 7520 ToBeginLoc, E->getTrait(), ToQueriedExpression, E->getValue(), 7521 ToEndLoc, ToType); 7522 } 7523 7524 ExpectedStmt ASTNodeImporter::VisitOpaqueValueExpr(OpaqueValueExpr *E) { 7525 Error Err = Error::success(); 7526 auto ToLocation = importChecked(Err, E->getLocation()); 7527 auto ToType = importChecked(Err, E->getType()); 7528 auto ToSourceExpr = importChecked(Err, E->getSourceExpr()); 7529 if (Err) 7530 return std::move(Err); 7531 7532 return new (Importer.getToContext()) OpaqueValueExpr( 7533 ToLocation, ToType, E->getValueKind(), E->getObjectKind(), ToSourceExpr); 7534 } 7535 7536 ExpectedStmt ASTNodeImporter::VisitArraySubscriptExpr(ArraySubscriptExpr *E) { 7537 Error Err = Error::success(); 7538 auto ToLHS = importChecked(Err, E->getLHS()); 7539 auto ToRHS = importChecked(Err, E->getRHS()); 7540 auto ToType = importChecked(Err, E->getType()); 7541 auto ToRBracketLoc = importChecked(Err, E->getRBracketLoc()); 7542 if (Err) 7543 return std::move(Err); 7544 7545 return new (Importer.getToContext()) ArraySubscriptExpr( 7546 ToLHS, ToRHS, ToType, E->getValueKind(), E->getObjectKind(), 7547 ToRBracketLoc); 7548 } 7549 7550 ExpectedStmt 7551 ASTNodeImporter::VisitCompoundAssignOperator(CompoundAssignOperator *E) { 7552 Error Err = Error::success(); 7553 auto ToLHS = importChecked(Err, E->getLHS()); 7554 auto ToRHS = importChecked(Err, E->getRHS()); 7555 auto ToType = importChecked(Err, E->getType()); 7556 auto ToComputationLHSType = importChecked(Err, E->getComputationLHSType()); 7557 auto ToComputationResultType = 7558 importChecked(Err, E->getComputationResultType()); 7559 auto ToOperatorLoc = importChecked(Err, E->getOperatorLoc()); 7560 if (Err) 7561 return std::move(Err); 7562 7563 return CompoundAssignOperator::Create( 7564 Importer.getToContext(), ToLHS, ToRHS, E->getOpcode(), ToType, 7565 E->getValueKind(), E->getObjectKind(), ToOperatorLoc, 7566 E->getFPFeatures(), 7567 ToComputationLHSType, ToComputationResultType); 7568 } 7569 7570 Expected<CXXCastPath> 7571 ASTNodeImporter::ImportCastPath(CastExpr *CE) { 7572 CXXCastPath Path; 7573 for (auto I = CE->path_begin(), E = CE->path_end(); I != E; ++I) { 7574 if (auto SpecOrErr = import(*I)) 7575 Path.push_back(*SpecOrErr); 7576 else 7577 return SpecOrErr.takeError(); 7578 } 7579 return Path; 7580 } 7581 7582 ExpectedStmt ASTNodeImporter::VisitImplicitCastExpr(ImplicitCastExpr *E) { 7583 ExpectedType ToTypeOrErr = import(E->getType()); 7584 if (!ToTypeOrErr) 7585 return ToTypeOrErr.takeError(); 7586 7587 ExpectedExpr ToSubExprOrErr = import(E->getSubExpr()); 7588 if (!ToSubExprOrErr) 7589 return ToSubExprOrErr.takeError(); 7590 7591 Expected<CXXCastPath> ToBasePathOrErr = ImportCastPath(E); 7592 if (!ToBasePathOrErr) 7593 return ToBasePathOrErr.takeError(); 7594 7595 return ImplicitCastExpr::Create( 7596 Importer.getToContext(), *ToTypeOrErr, E->getCastKind(), *ToSubExprOrErr, 7597 &(*ToBasePathOrErr), E->getValueKind(), E->getFPFeatures()); 7598 } 7599 7600 ExpectedStmt ASTNodeImporter::VisitExplicitCastExpr(ExplicitCastExpr *E) { 7601 Error Err = Error::success(); 7602 auto ToType = importChecked(Err, E->getType()); 7603 auto ToSubExpr = importChecked(Err, E->getSubExpr()); 7604 auto ToTypeInfoAsWritten = importChecked(Err, E->getTypeInfoAsWritten()); 7605 if (Err) 7606 return std::move(Err); 7607 7608 Expected<CXXCastPath> ToBasePathOrErr = ImportCastPath(E); 7609 if (!ToBasePathOrErr) 7610 return ToBasePathOrErr.takeError(); 7611 CXXCastPath *ToBasePath = &(*ToBasePathOrErr); 7612 7613 switch (E->getStmtClass()) { 7614 case Stmt::CStyleCastExprClass: { 7615 auto *CCE = cast<CStyleCastExpr>(E); 7616 ExpectedSLoc ToLParenLocOrErr = import(CCE->getLParenLoc()); 7617 if (!ToLParenLocOrErr) 7618 return ToLParenLocOrErr.takeError(); 7619 ExpectedSLoc ToRParenLocOrErr = import(CCE->getRParenLoc()); 7620 if (!ToRParenLocOrErr) 7621 return ToRParenLocOrErr.takeError(); 7622 return CStyleCastExpr::Create( 7623 Importer.getToContext(), ToType, E->getValueKind(), E->getCastKind(), 7624 ToSubExpr, ToBasePath, CCE->getFPFeatures(), ToTypeInfoAsWritten, 7625 *ToLParenLocOrErr, *ToRParenLocOrErr); 7626 } 7627 7628 case Stmt::CXXFunctionalCastExprClass: { 7629 auto *FCE = cast<CXXFunctionalCastExpr>(E); 7630 ExpectedSLoc ToLParenLocOrErr = import(FCE->getLParenLoc()); 7631 if (!ToLParenLocOrErr) 7632 return ToLParenLocOrErr.takeError(); 7633 ExpectedSLoc ToRParenLocOrErr = import(FCE->getRParenLoc()); 7634 if (!ToRParenLocOrErr) 7635 return ToRParenLocOrErr.takeError(); 7636 return CXXFunctionalCastExpr::Create( 7637 Importer.getToContext(), ToType, E->getValueKind(), ToTypeInfoAsWritten, 7638 E->getCastKind(), ToSubExpr, ToBasePath, FCE->getFPFeatures(), 7639 *ToLParenLocOrErr, *ToRParenLocOrErr); 7640 } 7641 7642 case Stmt::ObjCBridgedCastExprClass: { 7643 auto *OCE = cast<ObjCBridgedCastExpr>(E); 7644 ExpectedSLoc ToLParenLocOrErr = import(OCE->getLParenLoc()); 7645 if (!ToLParenLocOrErr) 7646 return ToLParenLocOrErr.takeError(); 7647 ExpectedSLoc ToBridgeKeywordLocOrErr = import(OCE->getBridgeKeywordLoc()); 7648 if (!ToBridgeKeywordLocOrErr) 7649 return ToBridgeKeywordLocOrErr.takeError(); 7650 return new (Importer.getToContext()) ObjCBridgedCastExpr( 7651 *ToLParenLocOrErr, OCE->getBridgeKind(), E->getCastKind(), 7652 *ToBridgeKeywordLocOrErr, ToTypeInfoAsWritten, ToSubExpr); 7653 } 7654 default: 7655 llvm_unreachable("Cast expression of unsupported type!"); 7656 return make_error<ASTImportError>(ASTImportError::UnsupportedConstruct); 7657 } 7658 } 7659 7660 ExpectedStmt ASTNodeImporter::VisitOffsetOfExpr(OffsetOfExpr *E) { 7661 SmallVector<OffsetOfNode, 4> ToNodes; 7662 for (int I = 0, N = E->getNumComponents(); I < N; ++I) { 7663 const OffsetOfNode &FromNode = E->getComponent(I); 7664 7665 SourceLocation ToBeginLoc, ToEndLoc; 7666 7667 if (FromNode.getKind() != OffsetOfNode::Base) { 7668 Error Err = Error::success(); 7669 ToBeginLoc = importChecked(Err, FromNode.getBeginLoc()); 7670 ToEndLoc = importChecked(Err, FromNode.getEndLoc()); 7671 if (Err) 7672 return std::move(Err); 7673 } 7674 7675 switch (FromNode.getKind()) { 7676 case OffsetOfNode::Array: 7677 ToNodes.push_back( 7678 OffsetOfNode(ToBeginLoc, FromNode.getArrayExprIndex(), ToEndLoc)); 7679 break; 7680 case OffsetOfNode::Base: { 7681 auto ToBSOrErr = import(FromNode.getBase()); 7682 if (!ToBSOrErr) 7683 return ToBSOrErr.takeError(); 7684 ToNodes.push_back(OffsetOfNode(*ToBSOrErr)); 7685 break; 7686 } 7687 case OffsetOfNode::Field: { 7688 auto ToFieldOrErr = import(FromNode.getField()); 7689 if (!ToFieldOrErr) 7690 return ToFieldOrErr.takeError(); 7691 ToNodes.push_back(OffsetOfNode(ToBeginLoc, *ToFieldOrErr, ToEndLoc)); 7692 break; 7693 } 7694 case OffsetOfNode::Identifier: { 7695 IdentifierInfo *ToII = Importer.Import(FromNode.getFieldName()); 7696 ToNodes.push_back(OffsetOfNode(ToBeginLoc, ToII, ToEndLoc)); 7697 break; 7698 } 7699 } 7700 } 7701 7702 SmallVector<Expr *, 4> ToExprs(E->getNumExpressions()); 7703 for (int I = 0, N = E->getNumExpressions(); I < N; ++I) { 7704 ExpectedExpr ToIndexExprOrErr = import(E->getIndexExpr(I)); 7705 if (!ToIndexExprOrErr) 7706 return ToIndexExprOrErr.takeError(); 7707 ToExprs[I] = *ToIndexExprOrErr; 7708 } 7709 7710 Error Err = Error::success(); 7711 auto ToType = importChecked(Err, E->getType()); 7712 auto ToTypeSourceInfo = importChecked(Err, E->getTypeSourceInfo()); 7713 auto ToOperatorLoc = importChecked(Err, E->getOperatorLoc()); 7714 auto ToRParenLoc = importChecked(Err, E->getRParenLoc()); 7715 if (Err) 7716 return std::move(Err); 7717 7718 return OffsetOfExpr::Create( 7719 Importer.getToContext(), ToType, ToOperatorLoc, ToTypeSourceInfo, ToNodes, 7720 ToExprs, ToRParenLoc); 7721 } 7722 7723 ExpectedStmt ASTNodeImporter::VisitCXXNoexceptExpr(CXXNoexceptExpr *E) { 7724 Error Err = Error::success(); 7725 auto ToType = importChecked(Err, E->getType()); 7726 auto ToOperand = importChecked(Err, E->getOperand()); 7727 auto ToBeginLoc = importChecked(Err, E->getBeginLoc()); 7728 auto ToEndLoc = importChecked(Err, E->getEndLoc()); 7729 if (Err) 7730 return std::move(Err); 7731 7732 CanThrowResult ToCanThrow; 7733 if (E->isValueDependent()) 7734 ToCanThrow = CT_Dependent; 7735 else 7736 ToCanThrow = E->getValue() ? CT_Can : CT_Cannot; 7737 7738 return new (Importer.getToContext()) CXXNoexceptExpr( 7739 ToType, ToOperand, ToCanThrow, ToBeginLoc, ToEndLoc); 7740 } 7741 7742 ExpectedStmt ASTNodeImporter::VisitCXXThrowExpr(CXXThrowExpr *E) { 7743 Error Err = Error::success(); 7744 auto ToSubExpr = importChecked(Err, E->getSubExpr()); 7745 auto ToType = importChecked(Err, E->getType()); 7746 auto ToThrowLoc = importChecked(Err, E->getThrowLoc()); 7747 if (Err) 7748 return std::move(Err); 7749 7750 return new (Importer.getToContext()) CXXThrowExpr( 7751 ToSubExpr, ToType, ToThrowLoc, E->isThrownVariableInScope()); 7752 } 7753 7754 ExpectedStmt ASTNodeImporter::VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) { 7755 ExpectedSLoc ToUsedLocOrErr = import(E->getUsedLocation()); 7756 if (!ToUsedLocOrErr) 7757 return ToUsedLocOrErr.takeError(); 7758 7759 auto ToParamOrErr = import(E->getParam()); 7760 if (!ToParamOrErr) 7761 return ToParamOrErr.takeError(); 7762 7763 auto UsedContextOrErr = Importer.ImportContext(E->getUsedContext()); 7764 if (!UsedContextOrErr) 7765 return UsedContextOrErr.takeError(); 7766 7767 // Import the default arg if it was not imported yet. 7768 // This is needed because it can happen that during the import of the 7769 // default expression (from VisitParmVarDecl) the same ParmVarDecl is 7770 // encountered here. The default argument for a ParmVarDecl is set in the 7771 // ParmVarDecl only after it is imported (set in VisitParmVarDecl if not here, 7772 // see VisitParmVarDecl). 7773 ParmVarDecl *ToParam = *ToParamOrErr; 7774 if (!ToParam->getDefaultArg()) { 7775 std::optional<ParmVarDecl *> FromParam = 7776 Importer.getImportedFromDecl(ToParam); 7777 assert(FromParam && "ParmVarDecl was not imported?"); 7778 7779 if (Error Err = ImportDefaultArgOfParmVarDecl(*FromParam, ToParam)) 7780 return std::move(Err); 7781 } 7782 Expr *RewrittenInit = nullptr; 7783 if (E->hasRewrittenInit()) { 7784 ExpectedExpr ExprOrErr = import(E->getRewrittenExpr()); 7785 if (!ExprOrErr) 7786 return ExprOrErr.takeError(); 7787 RewrittenInit = ExprOrErr.get(); 7788 } 7789 return CXXDefaultArgExpr::Create(Importer.getToContext(), *ToUsedLocOrErr, 7790 *ToParamOrErr, RewrittenInit, 7791 *UsedContextOrErr); 7792 } 7793 7794 ExpectedStmt 7795 ASTNodeImporter::VisitCXXScalarValueInitExpr(CXXScalarValueInitExpr *E) { 7796 Error Err = Error::success(); 7797 auto ToType = importChecked(Err, E->getType()); 7798 auto ToTypeSourceInfo = importChecked(Err, E->getTypeSourceInfo()); 7799 auto ToRParenLoc = importChecked(Err, E->getRParenLoc()); 7800 if (Err) 7801 return std::move(Err); 7802 7803 return new (Importer.getToContext()) CXXScalarValueInitExpr( 7804 ToType, ToTypeSourceInfo, ToRParenLoc); 7805 } 7806 7807 ExpectedStmt 7808 ASTNodeImporter::VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) { 7809 ExpectedExpr ToSubExprOrErr = import(E->getSubExpr()); 7810 if (!ToSubExprOrErr) 7811 return ToSubExprOrErr.takeError(); 7812 7813 auto ToDtorOrErr = import(E->getTemporary()->getDestructor()); 7814 if (!ToDtorOrErr) 7815 return ToDtorOrErr.takeError(); 7816 7817 ASTContext &ToCtx = Importer.getToContext(); 7818 CXXTemporary *Temp = CXXTemporary::Create(ToCtx, *ToDtorOrErr); 7819 return CXXBindTemporaryExpr::Create(ToCtx, Temp, *ToSubExprOrErr); 7820 } 7821 7822 ExpectedStmt 7823 7824 ASTNodeImporter::VisitCXXTemporaryObjectExpr(CXXTemporaryObjectExpr *E) { 7825 Error Err = Error::success(); 7826 auto ToConstructor = importChecked(Err, E->getConstructor()); 7827 auto ToType = importChecked(Err, E->getType()); 7828 auto ToTypeSourceInfo = importChecked(Err, E->getTypeSourceInfo()); 7829 auto ToParenOrBraceRange = importChecked(Err, E->getParenOrBraceRange()); 7830 if (Err) 7831 return std::move(Err); 7832 7833 SmallVector<Expr *, 8> ToArgs(E->getNumArgs()); 7834 if (Error Err = ImportContainerChecked(E->arguments(), ToArgs)) 7835 return std::move(Err); 7836 7837 return CXXTemporaryObjectExpr::Create( 7838 Importer.getToContext(), ToConstructor, ToType, ToTypeSourceInfo, ToArgs, 7839 ToParenOrBraceRange, E->hadMultipleCandidates(), 7840 E->isListInitialization(), E->isStdInitListInitialization(), 7841 E->requiresZeroInitialization()); 7842 } 7843 7844 ExpectedDecl ASTNodeImporter::VisitLifetimeExtendedTemporaryDecl( 7845 LifetimeExtendedTemporaryDecl *D) { 7846 DeclContext *DC, *LexicalDC; 7847 if (Error Err = ImportDeclContext(D, DC, LexicalDC)) 7848 return std::move(Err); 7849 7850 Error Err = Error::success(); 7851 auto Temporary = importChecked(Err, D->getTemporaryExpr()); 7852 auto ExtendingDecl = importChecked(Err, D->getExtendingDecl()); 7853 if (Err) 7854 return std::move(Err); 7855 // FIXME: Should ManglingNumber get numbers associated with 'to' context? 7856 7857 LifetimeExtendedTemporaryDecl *To; 7858 if (GetImportedOrCreateDecl(To, D, Temporary, ExtendingDecl, 7859 D->getManglingNumber())) 7860 return To; 7861 7862 To->setLexicalDeclContext(LexicalDC); 7863 LexicalDC->addDeclInternal(To); 7864 return To; 7865 } 7866 7867 ExpectedStmt 7868 ASTNodeImporter::VisitMaterializeTemporaryExpr(MaterializeTemporaryExpr *E) { 7869 Error Err = Error::success(); 7870 auto ToType = importChecked(Err, E->getType()); 7871 Expr *ToTemporaryExpr = importChecked( 7872 Err, E->getLifetimeExtendedTemporaryDecl() ? nullptr : E->getSubExpr()); 7873 auto ToMaterializedDecl = 7874 importChecked(Err, E->getLifetimeExtendedTemporaryDecl()); 7875 if (Err) 7876 return std::move(Err); 7877 7878 if (!ToTemporaryExpr) 7879 ToTemporaryExpr = cast<Expr>(ToMaterializedDecl->getTemporaryExpr()); 7880 7881 auto *ToMTE = new (Importer.getToContext()) MaterializeTemporaryExpr( 7882 ToType, ToTemporaryExpr, E->isBoundToLvalueReference(), 7883 ToMaterializedDecl); 7884 7885 return ToMTE; 7886 } 7887 7888 ExpectedStmt ASTNodeImporter::VisitPackExpansionExpr(PackExpansionExpr *E) { 7889 Error Err = Error::success(); 7890 auto ToType = importChecked(Err, E->getType()); 7891 auto ToPattern = importChecked(Err, E->getPattern()); 7892 auto ToEllipsisLoc = importChecked(Err, E->getEllipsisLoc()); 7893 if (Err) 7894 return std::move(Err); 7895 7896 return new (Importer.getToContext()) PackExpansionExpr( 7897 ToType, ToPattern, ToEllipsisLoc, E->getNumExpansions()); 7898 } 7899 7900 ExpectedStmt ASTNodeImporter::VisitSizeOfPackExpr(SizeOfPackExpr *E) { 7901 Error Err = Error::success(); 7902 auto ToOperatorLoc = importChecked(Err, E->getOperatorLoc()); 7903 auto ToPack = importChecked(Err, E->getPack()); 7904 auto ToPackLoc = importChecked(Err, E->getPackLoc()); 7905 auto ToRParenLoc = importChecked(Err, E->getRParenLoc()); 7906 if (Err) 7907 return std::move(Err); 7908 7909 std::optional<unsigned> Length; 7910 if (!E->isValueDependent()) 7911 Length = E->getPackLength(); 7912 7913 SmallVector<TemplateArgument, 8> ToPartialArguments; 7914 if (E->isPartiallySubstituted()) { 7915 if (Error Err = ImportTemplateArguments(E->getPartialArguments(), 7916 ToPartialArguments)) 7917 return std::move(Err); 7918 } 7919 7920 return SizeOfPackExpr::Create( 7921 Importer.getToContext(), ToOperatorLoc, ToPack, ToPackLoc, ToRParenLoc, 7922 Length, ToPartialArguments); 7923 } 7924 7925 7926 ExpectedStmt ASTNodeImporter::VisitCXXNewExpr(CXXNewExpr *E) { 7927 Error Err = Error::success(); 7928 auto ToOperatorNew = importChecked(Err, E->getOperatorNew()); 7929 auto ToOperatorDelete = importChecked(Err, E->getOperatorDelete()); 7930 auto ToTypeIdParens = importChecked(Err, E->getTypeIdParens()); 7931 auto ToArraySize = importChecked(Err, E->getArraySize()); 7932 auto ToInitializer = importChecked(Err, E->getInitializer()); 7933 auto ToType = importChecked(Err, E->getType()); 7934 auto ToAllocatedTypeSourceInfo = 7935 importChecked(Err, E->getAllocatedTypeSourceInfo()); 7936 auto ToSourceRange = importChecked(Err, E->getSourceRange()); 7937 auto ToDirectInitRange = importChecked(Err, E->getDirectInitRange()); 7938 if (Err) 7939 return std::move(Err); 7940 7941 SmallVector<Expr *, 4> ToPlacementArgs(E->getNumPlacementArgs()); 7942 if (Error Err = 7943 ImportContainerChecked(E->placement_arguments(), ToPlacementArgs)) 7944 return std::move(Err); 7945 7946 return CXXNewExpr::Create( 7947 Importer.getToContext(), E->isGlobalNew(), ToOperatorNew, 7948 ToOperatorDelete, E->passAlignment(), E->doesUsualArrayDeleteWantSize(), 7949 ToPlacementArgs, ToTypeIdParens, ToArraySize, E->getInitializationStyle(), 7950 ToInitializer, ToType, ToAllocatedTypeSourceInfo, ToSourceRange, 7951 ToDirectInitRange); 7952 } 7953 7954 ExpectedStmt ASTNodeImporter::VisitCXXDeleteExpr(CXXDeleteExpr *E) { 7955 Error Err = Error::success(); 7956 auto ToType = importChecked(Err, E->getType()); 7957 auto ToOperatorDelete = importChecked(Err, E->getOperatorDelete()); 7958 auto ToArgument = importChecked(Err, E->getArgument()); 7959 auto ToBeginLoc = importChecked(Err, E->getBeginLoc()); 7960 if (Err) 7961 return std::move(Err); 7962 7963 return new (Importer.getToContext()) CXXDeleteExpr( 7964 ToType, E->isGlobalDelete(), E->isArrayForm(), E->isArrayFormAsWritten(), 7965 E->doesUsualArrayDeleteWantSize(), ToOperatorDelete, ToArgument, 7966 ToBeginLoc); 7967 } 7968 7969 ExpectedStmt ASTNodeImporter::VisitCXXConstructExpr(CXXConstructExpr *E) { 7970 Error Err = Error::success(); 7971 auto ToType = importChecked(Err, E->getType()); 7972 auto ToLocation = importChecked(Err, E->getLocation()); 7973 auto ToConstructor = importChecked(Err, E->getConstructor()); 7974 auto ToParenOrBraceRange = importChecked(Err, E->getParenOrBraceRange()); 7975 if (Err) 7976 return std::move(Err); 7977 7978 SmallVector<Expr *, 6> ToArgs(E->getNumArgs()); 7979 if (Error Err = ImportContainerChecked(E->arguments(), ToArgs)) 7980 return std::move(Err); 7981 7982 CXXConstructExpr *ToE = CXXConstructExpr::Create( 7983 Importer.getToContext(), ToType, ToLocation, ToConstructor, 7984 E->isElidable(), ToArgs, E->hadMultipleCandidates(), 7985 E->isListInitialization(), E->isStdInitListInitialization(), 7986 E->requiresZeroInitialization(), E->getConstructionKind(), 7987 ToParenOrBraceRange); 7988 ToE->setIsImmediateEscalating(E->isImmediateEscalating()); 7989 return ToE; 7990 } 7991 7992 ExpectedStmt ASTNodeImporter::VisitExprWithCleanups(ExprWithCleanups *E) { 7993 ExpectedExpr ToSubExprOrErr = import(E->getSubExpr()); 7994 if (!ToSubExprOrErr) 7995 return ToSubExprOrErr.takeError(); 7996 7997 SmallVector<ExprWithCleanups::CleanupObject, 8> ToObjects(E->getNumObjects()); 7998 if (Error Err = ImportContainerChecked(E->getObjects(), ToObjects)) 7999 return std::move(Err); 8000 8001 return ExprWithCleanups::Create( 8002 Importer.getToContext(), *ToSubExprOrErr, E->cleanupsHaveSideEffects(), 8003 ToObjects); 8004 } 8005 8006 ExpectedStmt ASTNodeImporter::VisitCXXMemberCallExpr(CXXMemberCallExpr *E) { 8007 Error Err = Error::success(); 8008 auto ToCallee = importChecked(Err, E->getCallee()); 8009 auto ToType = importChecked(Err, E->getType()); 8010 auto ToRParenLoc = importChecked(Err, E->getRParenLoc()); 8011 if (Err) 8012 return std::move(Err); 8013 8014 SmallVector<Expr *, 4> ToArgs(E->getNumArgs()); 8015 if (Error Err = ImportContainerChecked(E->arguments(), ToArgs)) 8016 return std::move(Err); 8017 8018 return CXXMemberCallExpr::Create(Importer.getToContext(), ToCallee, ToArgs, 8019 ToType, E->getValueKind(), ToRParenLoc, 8020 E->getFPFeatures()); 8021 } 8022 8023 ExpectedStmt ASTNodeImporter::VisitCXXThisExpr(CXXThisExpr *E) { 8024 ExpectedType ToTypeOrErr = import(E->getType()); 8025 if (!ToTypeOrErr) 8026 return ToTypeOrErr.takeError(); 8027 8028 ExpectedSLoc ToLocationOrErr = import(E->getLocation()); 8029 if (!ToLocationOrErr) 8030 return ToLocationOrErr.takeError(); 8031 8032 return new (Importer.getToContext()) CXXThisExpr( 8033 *ToLocationOrErr, *ToTypeOrErr, E->isImplicit()); 8034 } 8035 8036 ExpectedStmt ASTNodeImporter::VisitCXXBoolLiteralExpr(CXXBoolLiteralExpr *E) { 8037 ExpectedType ToTypeOrErr = import(E->getType()); 8038 if (!ToTypeOrErr) 8039 return ToTypeOrErr.takeError(); 8040 8041 ExpectedSLoc ToLocationOrErr = import(E->getLocation()); 8042 if (!ToLocationOrErr) 8043 return ToLocationOrErr.takeError(); 8044 8045 return CXXBoolLiteralExpr::Create(Importer.getToContext(), E->getValue(), 8046 *ToTypeOrErr, *ToLocationOrErr); 8047 } 8048 8049 ExpectedStmt ASTNodeImporter::VisitMemberExpr(MemberExpr *E) { 8050 Error Err = Error::success(); 8051 auto ToBase = importChecked(Err, E->getBase()); 8052 auto ToOperatorLoc = importChecked(Err, E->getOperatorLoc()); 8053 auto ToQualifierLoc = importChecked(Err, E->getQualifierLoc()); 8054 auto ToTemplateKeywordLoc = importChecked(Err, E->getTemplateKeywordLoc()); 8055 auto ToMemberDecl = importChecked(Err, E->getMemberDecl()); 8056 auto ToType = importChecked(Err, E->getType()); 8057 auto ToDecl = importChecked(Err, E->getFoundDecl().getDecl()); 8058 auto ToName = importChecked(Err, E->getMemberNameInfo().getName()); 8059 auto ToLoc = importChecked(Err, E->getMemberNameInfo().getLoc()); 8060 if (Err) 8061 return std::move(Err); 8062 8063 DeclAccessPair ToFoundDecl = 8064 DeclAccessPair::make(ToDecl, E->getFoundDecl().getAccess()); 8065 8066 DeclarationNameInfo ToMemberNameInfo(ToName, ToLoc); 8067 8068 TemplateArgumentListInfo ToTAInfo, *ResInfo = nullptr; 8069 if (E->hasExplicitTemplateArgs()) { 8070 if (Error Err = 8071 ImportTemplateArgumentListInfo(E->getLAngleLoc(), E->getRAngleLoc(), 8072 E->template_arguments(), ToTAInfo)) 8073 return std::move(Err); 8074 ResInfo = &ToTAInfo; 8075 } 8076 8077 return MemberExpr::Create(Importer.getToContext(), ToBase, E->isArrow(), 8078 ToOperatorLoc, ToQualifierLoc, ToTemplateKeywordLoc, 8079 ToMemberDecl, ToFoundDecl, ToMemberNameInfo, 8080 ResInfo, ToType, E->getValueKind(), 8081 E->getObjectKind(), E->isNonOdrUse()); 8082 } 8083 8084 ExpectedStmt 8085 ASTNodeImporter::VisitCXXPseudoDestructorExpr(CXXPseudoDestructorExpr *E) { 8086 Error Err = Error::success(); 8087 auto ToBase = importChecked(Err, E->getBase()); 8088 auto ToOperatorLoc = importChecked(Err, E->getOperatorLoc()); 8089 auto ToQualifierLoc = importChecked(Err, E->getQualifierLoc()); 8090 auto ToScopeTypeInfo = importChecked(Err, E->getScopeTypeInfo()); 8091 auto ToColonColonLoc = importChecked(Err, E->getColonColonLoc()); 8092 auto ToTildeLoc = importChecked(Err, E->getTildeLoc()); 8093 if (Err) 8094 return std::move(Err); 8095 8096 PseudoDestructorTypeStorage Storage; 8097 if (IdentifierInfo *FromII = E->getDestroyedTypeIdentifier()) { 8098 IdentifierInfo *ToII = Importer.Import(FromII); 8099 ExpectedSLoc ToDestroyedTypeLocOrErr = import(E->getDestroyedTypeLoc()); 8100 if (!ToDestroyedTypeLocOrErr) 8101 return ToDestroyedTypeLocOrErr.takeError(); 8102 Storage = PseudoDestructorTypeStorage(ToII, *ToDestroyedTypeLocOrErr); 8103 } else { 8104 if (auto ToTIOrErr = import(E->getDestroyedTypeInfo())) 8105 Storage = PseudoDestructorTypeStorage(*ToTIOrErr); 8106 else 8107 return ToTIOrErr.takeError(); 8108 } 8109 8110 return new (Importer.getToContext()) CXXPseudoDestructorExpr( 8111 Importer.getToContext(), ToBase, E->isArrow(), ToOperatorLoc, 8112 ToQualifierLoc, ToScopeTypeInfo, ToColonColonLoc, ToTildeLoc, Storage); 8113 } 8114 8115 ExpectedStmt ASTNodeImporter::VisitCXXDependentScopeMemberExpr( 8116 CXXDependentScopeMemberExpr *E) { 8117 Error Err = Error::success(); 8118 auto ToType = importChecked(Err, E->getType()); 8119 auto ToOperatorLoc = importChecked(Err, E->getOperatorLoc()); 8120 auto ToQualifierLoc = importChecked(Err, E->getQualifierLoc()); 8121 auto ToTemplateKeywordLoc = importChecked(Err, E->getTemplateKeywordLoc()); 8122 auto ToFirstQualifierFoundInScope = 8123 importChecked(Err, E->getFirstQualifierFoundInScope()); 8124 if (Err) 8125 return std::move(Err); 8126 8127 Expr *ToBase = nullptr; 8128 if (!E->isImplicitAccess()) { 8129 if (ExpectedExpr ToBaseOrErr = import(E->getBase())) 8130 ToBase = *ToBaseOrErr; 8131 else 8132 return ToBaseOrErr.takeError(); 8133 } 8134 8135 TemplateArgumentListInfo ToTAInfo, *ResInfo = nullptr; 8136 8137 if (E->hasExplicitTemplateArgs()) { 8138 if (Error Err = 8139 ImportTemplateArgumentListInfo(E->getLAngleLoc(), E->getRAngleLoc(), 8140 E->template_arguments(), ToTAInfo)) 8141 return std::move(Err); 8142 ResInfo = &ToTAInfo; 8143 } 8144 auto ToMember = importChecked(Err, E->getMember()); 8145 auto ToMemberLoc = importChecked(Err, E->getMemberLoc()); 8146 if (Err) 8147 return std::move(Err); 8148 DeclarationNameInfo ToMemberNameInfo(ToMember, ToMemberLoc); 8149 8150 // Import additional name location/type info. 8151 if (Error Err = 8152 ImportDeclarationNameLoc(E->getMemberNameInfo(), ToMemberNameInfo)) 8153 return std::move(Err); 8154 8155 return CXXDependentScopeMemberExpr::Create( 8156 Importer.getToContext(), ToBase, ToType, E->isArrow(), ToOperatorLoc, 8157 ToQualifierLoc, ToTemplateKeywordLoc, ToFirstQualifierFoundInScope, 8158 ToMemberNameInfo, ResInfo); 8159 } 8160 8161 ExpectedStmt 8162 ASTNodeImporter::VisitDependentScopeDeclRefExpr(DependentScopeDeclRefExpr *E) { 8163 Error Err = Error::success(); 8164 auto ToQualifierLoc = importChecked(Err, E->getQualifierLoc()); 8165 auto ToTemplateKeywordLoc = importChecked(Err, E->getTemplateKeywordLoc()); 8166 auto ToDeclName = importChecked(Err, E->getDeclName()); 8167 auto ToNameLoc = importChecked(Err, E->getNameInfo().getLoc()); 8168 auto ToLAngleLoc = importChecked(Err, E->getLAngleLoc()); 8169 auto ToRAngleLoc = importChecked(Err, E->getRAngleLoc()); 8170 if (Err) 8171 return std::move(Err); 8172 8173 DeclarationNameInfo ToNameInfo(ToDeclName, ToNameLoc); 8174 if (Error Err = ImportDeclarationNameLoc(E->getNameInfo(), ToNameInfo)) 8175 return std::move(Err); 8176 8177 TemplateArgumentListInfo ToTAInfo(ToLAngleLoc, ToRAngleLoc); 8178 TemplateArgumentListInfo *ResInfo = nullptr; 8179 if (E->hasExplicitTemplateArgs()) { 8180 if (Error Err = 8181 ImportTemplateArgumentListInfo(E->template_arguments(), ToTAInfo)) 8182 return std::move(Err); 8183 ResInfo = &ToTAInfo; 8184 } 8185 8186 return DependentScopeDeclRefExpr::Create( 8187 Importer.getToContext(), ToQualifierLoc, ToTemplateKeywordLoc, 8188 ToNameInfo, ResInfo); 8189 } 8190 8191 ExpectedStmt ASTNodeImporter::VisitCXXUnresolvedConstructExpr( 8192 CXXUnresolvedConstructExpr *E) { 8193 Error Err = Error::success(); 8194 auto ToLParenLoc = importChecked(Err, E->getLParenLoc()); 8195 auto ToRParenLoc = importChecked(Err, E->getRParenLoc()); 8196 auto ToType = importChecked(Err, E->getType()); 8197 auto ToTypeSourceInfo = importChecked(Err, E->getTypeSourceInfo()); 8198 if (Err) 8199 return std::move(Err); 8200 8201 SmallVector<Expr *, 8> ToArgs(E->getNumArgs()); 8202 if (Error Err = 8203 ImportArrayChecked(E->arg_begin(), E->arg_end(), ToArgs.begin())) 8204 return std::move(Err); 8205 8206 return CXXUnresolvedConstructExpr::Create( 8207 Importer.getToContext(), ToType, ToTypeSourceInfo, ToLParenLoc, 8208 llvm::ArrayRef(ToArgs), ToRParenLoc, E->isListInitialization()); 8209 } 8210 8211 ExpectedStmt 8212 ASTNodeImporter::VisitUnresolvedLookupExpr(UnresolvedLookupExpr *E) { 8213 Expected<CXXRecordDecl *> ToNamingClassOrErr = import(E->getNamingClass()); 8214 if (!ToNamingClassOrErr) 8215 return ToNamingClassOrErr.takeError(); 8216 8217 auto ToQualifierLocOrErr = import(E->getQualifierLoc()); 8218 if (!ToQualifierLocOrErr) 8219 return ToQualifierLocOrErr.takeError(); 8220 8221 Error Err = Error::success(); 8222 auto ToName = importChecked(Err, E->getName()); 8223 auto ToNameLoc = importChecked(Err, E->getNameLoc()); 8224 if (Err) 8225 return std::move(Err); 8226 DeclarationNameInfo ToNameInfo(ToName, ToNameLoc); 8227 8228 // Import additional name location/type info. 8229 if (Error Err = ImportDeclarationNameLoc(E->getNameInfo(), ToNameInfo)) 8230 return std::move(Err); 8231 8232 UnresolvedSet<8> ToDecls; 8233 for (auto *D : E->decls()) 8234 if (auto ToDOrErr = import(D)) 8235 ToDecls.addDecl(cast<NamedDecl>(*ToDOrErr)); 8236 else 8237 return ToDOrErr.takeError(); 8238 8239 if (E->hasExplicitTemplateArgs()) { 8240 TemplateArgumentListInfo ToTAInfo; 8241 if (Error Err = ImportTemplateArgumentListInfo( 8242 E->getLAngleLoc(), E->getRAngleLoc(), E->template_arguments(), 8243 ToTAInfo)) 8244 return std::move(Err); 8245 8246 ExpectedSLoc ToTemplateKeywordLocOrErr = import(E->getTemplateKeywordLoc()); 8247 if (!ToTemplateKeywordLocOrErr) 8248 return ToTemplateKeywordLocOrErr.takeError(); 8249 8250 return UnresolvedLookupExpr::Create( 8251 Importer.getToContext(), *ToNamingClassOrErr, *ToQualifierLocOrErr, 8252 *ToTemplateKeywordLocOrErr, ToNameInfo, E->requiresADL(), &ToTAInfo, 8253 ToDecls.begin(), ToDecls.end()); 8254 } 8255 8256 return UnresolvedLookupExpr::Create( 8257 Importer.getToContext(), *ToNamingClassOrErr, *ToQualifierLocOrErr, 8258 ToNameInfo, E->requiresADL(), E->isOverloaded(), ToDecls.begin(), 8259 ToDecls.end()); 8260 } 8261 8262 ExpectedStmt 8263 ASTNodeImporter::VisitUnresolvedMemberExpr(UnresolvedMemberExpr *E) { 8264 Error Err = Error::success(); 8265 auto ToType = importChecked(Err, E->getType()); 8266 auto ToOperatorLoc = importChecked(Err, E->getOperatorLoc()); 8267 auto ToQualifierLoc = importChecked(Err, E->getQualifierLoc()); 8268 auto ToTemplateKeywordLoc = importChecked(Err, E->getTemplateKeywordLoc()); 8269 auto ToName = importChecked(Err, E->getName()); 8270 auto ToNameLoc = importChecked(Err, E->getNameLoc()); 8271 if (Err) 8272 return std::move(Err); 8273 8274 DeclarationNameInfo ToNameInfo(ToName, ToNameLoc); 8275 // Import additional name location/type info. 8276 if (Error Err = ImportDeclarationNameLoc(E->getNameInfo(), ToNameInfo)) 8277 return std::move(Err); 8278 8279 UnresolvedSet<8> ToDecls; 8280 for (Decl *D : E->decls()) 8281 if (auto ToDOrErr = import(D)) 8282 ToDecls.addDecl(cast<NamedDecl>(*ToDOrErr)); 8283 else 8284 return ToDOrErr.takeError(); 8285 8286 TemplateArgumentListInfo ToTAInfo; 8287 TemplateArgumentListInfo *ResInfo = nullptr; 8288 if (E->hasExplicitTemplateArgs()) { 8289 TemplateArgumentListInfo FromTAInfo; 8290 E->copyTemplateArgumentsInto(FromTAInfo); 8291 if (Error Err = ImportTemplateArgumentListInfo(FromTAInfo, ToTAInfo)) 8292 return std::move(Err); 8293 ResInfo = &ToTAInfo; 8294 } 8295 8296 Expr *ToBase = nullptr; 8297 if (!E->isImplicitAccess()) { 8298 if (ExpectedExpr ToBaseOrErr = import(E->getBase())) 8299 ToBase = *ToBaseOrErr; 8300 else 8301 return ToBaseOrErr.takeError(); 8302 } 8303 8304 return UnresolvedMemberExpr::Create( 8305 Importer.getToContext(), E->hasUnresolvedUsing(), ToBase, ToType, 8306 E->isArrow(), ToOperatorLoc, ToQualifierLoc, ToTemplateKeywordLoc, 8307 ToNameInfo, ResInfo, ToDecls.begin(), ToDecls.end()); 8308 } 8309 8310 ExpectedStmt ASTNodeImporter::VisitCallExpr(CallExpr *E) { 8311 Error Err = Error::success(); 8312 auto ToCallee = importChecked(Err, E->getCallee()); 8313 auto ToType = importChecked(Err, E->getType()); 8314 auto ToRParenLoc = importChecked(Err, E->getRParenLoc()); 8315 if (Err) 8316 return std::move(Err); 8317 8318 unsigned NumArgs = E->getNumArgs(); 8319 llvm::SmallVector<Expr *, 2> ToArgs(NumArgs); 8320 if (Error Err = ImportContainerChecked(E->arguments(), ToArgs)) 8321 return std::move(Err); 8322 8323 if (const auto *OCE = dyn_cast<CXXOperatorCallExpr>(E)) { 8324 return CXXOperatorCallExpr::Create( 8325 Importer.getToContext(), OCE->getOperator(), ToCallee, ToArgs, ToType, 8326 OCE->getValueKind(), ToRParenLoc, OCE->getFPFeatures(), 8327 OCE->getADLCallKind()); 8328 } 8329 8330 return CallExpr::Create(Importer.getToContext(), ToCallee, ToArgs, ToType, 8331 E->getValueKind(), ToRParenLoc, E->getFPFeatures(), 8332 /*MinNumArgs=*/0, E->getADLCallKind()); 8333 } 8334 8335 ExpectedStmt ASTNodeImporter::VisitLambdaExpr(LambdaExpr *E) { 8336 CXXRecordDecl *FromClass = E->getLambdaClass(); 8337 auto ToClassOrErr = import(FromClass); 8338 if (!ToClassOrErr) 8339 return ToClassOrErr.takeError(); 8340 CXXRecordDecl *ToClass = *ToClassOrErr; 8341 8342 auto ToCallOpOrErr = import(E->getCallOperator()); 8343 if (!ToCallOpOrErr) 8344 return ToCallOpOrErr.takeError(); 8345 8346 SmallVector<Expr *, 8> ToCaptureInits(E->capture_size()); 8347 if (Error Err = ImportContainerChecked(E->capture_inits(), ToCaptureInits)) 8348 return std::move(Err); 8349 8350 Error Err = Error::success(); 8351 auto ToIntroducerRange = importChecked(Err, E->getIntroducerRange()); 8352 auto ToCaptureDefaultLoc = importChecked(Err, E->getCaptureDefaultLoc()); 8353 auto ToEndLoc = importChecked(Err, E->getEndLoc()); 8354 if (Err) 8355 return std::move(Err); 8356 8357 return LambdaExpr::Create(Importer.getToContext(), ToClass, ToIntroducerRange, 8358 E->getCaptureDefault(), ToCaptureDefaultLoc, 8359 E->hasExplicitParameters(), 8360 E->hasExplicitResultType(), ToCaptureInits, 8361 ToEndLoc, E->containsUnexpandedParameterPack()); 8362 } 8363 8364 8365 ExpectedStmt ASTNodeImporter::VisitInitListExpr(InitListExpr *E) { 8366 Error Err = Error::success(); 8367 auto ToLBraceLoc = importChecked(Err, E->getLBraceLoc()); 8368 auto ToRBraceLoc = importChecked(Err, E->getRBraceLoc()); 8369 auto ToType = importChecked(Err, E->getType()); 8370 if (Err) 8371 return std::move(Err); 8372 8373 SmallVector<Expr *, 4> ToExprs(E->getNumInits()); 8374 if (Error Err = ImportContainerChecked(E->inits(), ToExprs)) 8375 return std::move(Err); 8376 8377 ASTContext &ToCtx = Importer.getToContext(); 8378 InitListExpr *To = new (ToCtx) InitListExpr( 8379 ToCtx, ToLBraceLoc, ToExprs, ToRBraceLoc); 8380 To->setType(ToType); 8381 8382 if (E->hasArrayFiller()) { 8383 if (ExpectedExpr ToFillerOrErr = import(E->getArrayFiller())) 8384 To->setArrayFiller(*ToFillerOrErr); 8385 else 8386 return ToFillerOrErr.takeError(); 8387 } 8388 8389 if (FieldDecl *FromFD = E->getInitializedFieldInUnion()) { 8390 if (auto ToFDOrErr = import(FromFD)) 8391 To->setInitializedFieldInUnion(*ToFDOrErr); 8392 else 8393 return ToFDOrErr.takeError(); 8394 } 8395 8396 if (InitListExpr *SyntForm = E->getSyntacticForm()) { 8397 if (auto ToSyntFormOrErr = import(SyntForm)) 8398 To->setSyntacticForm(*ToSyntFormOrErr); 8399 else 8400 return ToSyntFormOrErr.takeError(); 8401 } 8402 8403 // Copy InitListExprBitfields, which are not handled in the ctor of 8404 // InitListExpr. 8405 To->sawArrayRangeDesignator(E->hadArrayRangeDesignator()); 8406 8407 return To; 8408 } 8409 8410 ExpectedStmt ASTNodeImporter::VisitCXXStdInitializerListExpr( 8411 CXXStdInitializerListExpr *E) { 8412 ExpectedType ToTypeOrErr = import(E->getType()); 8413 if (!ToTypeOrErr) 8414 return ToTypeOrErr.takeError(); 8415 8416 ExpectedExpr ToSubExprOrErr = import(E->getSubExpr()); 8417 if (!ToSubExprOrErr) 8418 return ToSubExprOrErr.takeError(); 8419 8420 return new (Importer.getToContext()) CXXStdInitializerListExpr( 8421 *ToTypeOrErr, *ToSubExprOrErr); 8422 } 8423 8424 ExpectedStmt ASTNodeImporter::VisitCXXInheritedCtorInitExpr( 8425 CXXInheritedCtorInitExpr *E) { 8426 Error Err = Error::success(); 8427 auto ToLocation = importChecked(Err, E->getLocation()); 8428 auto ToType = importChecked(Err, E->getType()); 8429 auto ToConstructor = importChecked(Err, E->getConstructor()); 8430 if (Err) 8431 return std::move(Err); 8432 8433 return new (Importer.getToContext()) CXXInheritedCtorInitExpr( 8434 ToLocation, ToType, ToConstructor, E->constructsVBase(), 8435 E->inheritedFromVBase()); 8436 } 8437 8438 ExpectedStmt ASTNodeImporter::VisitArrayInitLoopExpr(ArrayInitLoopExpr *E) { 8439 Error Err = Error::success(); 8440 auto ToType = importChecked(Err, E->getType()); 8441 auto ToCommonExpr = importChecked(Err, E->getCommonExpr()); 8442 auto ToSubExpr = importChecked(Err, E->getSubExpr()); 8443 if (Err) 8444 return std::move(Err); 8445 8446 return new (Importer.getToContext()) ArrayInitLoopExpr( 8447 ToType, ToCommonExpr, ToSubExpr); 8448 } 8449 8450 ExpectedStmt ASTNodeImporter::VisitArrayInitIndexExpr(ArrayInitIndexExpr *E) { 8451 ExpectedType ToTypeOrErr = import(E->getType()); 8452 if (!ToTypeOrErr) 8453 return ToTypeOrErr.takeError(); 8454 return new (Importer.getToContext()) ArrayInitIndexExpr(*ToTypeOrErr); 8455 } 8456 8457 ExpectedStmt ASTNodeImporter::VisitCXXDefaultInitExpr(CXXDefaultInitExpr *E) { 8458 ExpectedSLoc ToBeginLocOrErr = import(E->getBeginLoc()); 8459 if (!ToBeginLocOrErr) 8460 return ToBeginLocOrErr.takeError(); 8461 8462 auto ToFieldOrErr = import(E->getField()); 8463 if (!ToFieldOrErr) 8464 return ToFieldOrErr.takeError(); 8465 8466 auto UsedContextOrErr = Importer.ImportContext(E->getUsedContext()); 8467 if (!UsedContextOrErr) 8468 return UsedContextOrErr.takeError(); 8469 8470 FieldDecl *ToField = *ToFieldOrErr; 8471 assert(ToField->hasInClassInitializer() && 8472 "Field should have in-class initializer if there is a default init " 8473 "expression that uses it."); 8474 if (!ToField->getInClassInitializer()) { 8475 // The in-class initializer may be not yet set in "To" AST even if the 8476 // field is already there. This must be set here to make construction of 8477 // CXXDefaultInitExpr work. 8478 auto ToInClassInitializerOrErr = 8479 import(E->getField()->getInClassInitializer()); 8480 if (!ToInClassInitializerOrErr) 8481 return ToInClassInitializerOrErr.takeError(); 8482 ToField->setInClassInitializer(*ToInClassInitializerOrErr); 8483 } 8484 8485 Expr *RewrittenInit = nullptr; 8486 if (E->hasRewrittenInit()) { 8487 ExpectedExpr ExprOrErr = import(E->getRewrittenExpr()); 8488 if (!ExprOrErr) 8489 return ExprOrErr.takeError(); 8490 RewrittenInit = ExprOrErr.get(); 8491 } 8492 8493 return CXXDefaultInitExpr::Create(Importer.getToContext(), *ToBeginLocOrErr, 8494 ToField, *UsedContextOrErr, RewrittenInit); 8495 } 8496 8497 ExpectedStmt ASTNodeImporter::VisitCXXNamedCastExpr(CXXNamedCastExpr *E) { 8498 Error Err = Error::success(); 8499 auto ToType = importChecked(Err, E->getType()); 8500 auto ToSubExpr = importChecked(Err, E->getSubExpr()); 8501 auto ToTypeInfoAsWritten = importChecked(Err, E->getTypeInfoAsWritten()); 8502 auto ToOperatorLoc = importChecked(Err, E->getOperatorLoc()); 8503 auto ToRParenLoc = importChecked(Err, E->getRParenLoc()); 8504 auto ToAngleBrackets = importChecked(Err, E->getAngleBrackets()); 8505 if (Err) 8506 return std::move(Err); 8507 8508 ExprValueKind VK = E->getValueKind(); 8509 CastKind CK = E->getCastKind(); 8510 auto ToBasePathOrErr = ImportCastPath(E); 8511 if (!ToBasePathOrErr) 8512 return ToBasePathOrErr.takeError(); 8513 8514 if (auto CCE = dyn_cast<CXXStaticCastExpr>(E)) { 8515 return CXXStaticCastExpr::Create( 8516 Importer.getToContext(), ToType, VK, CK, ToSubExpr, &(*ToBasePathOrErr), 8517 ToTypeInfoAsWritten, CCE->getFPFeatures(), ToOperatorLoc, ToRParenLoc, 8518 ToAngleBrackets); 8519 } else if (isa<CXXDynamicCastExpr>(E)) { 8520 return CXXDynamicCastExpr::Create( 8521 Importer.getToContext(), ToType, VK, CK, ToSubExpr, &(*ToBasePathOrErr), 8522 ToTypeInfoAsWritten, ToOperatorLoc, ToRParenLoc, ToAngleBrackets); 8523 } else if (isa<CXXReinterpretCastExpr>(E)) { 8524 return CXXReinterpretCastExpr::Create( 8525 Importer.getToContext(), ToType, VK, CK, ToSubExpr, &(*ToBasePathOrErr), 8526 ToTypeInfoAsWritten, ToOperatorLoc, ToRParenLoc, ToAngleBrackets); 8527 } else if (isa<CXXConstCastExpr>(E)) { 8528 return CXXConstCastExpr::Create( 8529 Importer.getToContext(), ToType, VK, ToSubExpr, ToTypeInfoAsWritten, 8530 ToOperatorLoc, ToRParenLoc, ToAngleBrackets); 8531 } else { 8532 llvm_unreachable("Unknown cast type"); 8533 return make_error<ASTImportError>(); 8534 } 8535 } 8536 8537 ExpectedStmt ASTNodeImporter::VisitSubstNonTypeTemplateParmExpr( 8538 SubstNonTypeTemplateParmExpr *E) { 8539 Error Err = Error::success(); 8540 auto ToType = importChecked(Err, E->getType()); 8541 auto ToExprLoc = importChecked(Err, E->getExprLoc()); 8542 auto ToAssociatedDecl = importChecked(Err, E->getAssociatedDecl()); 8543 auto ToReplacement = importChecked(Err, E->getReplacement()); 8544 if (Err) 8545 return std::move(Err); 8546 8547 return new (Importer.getToContext()) SubstNonTypeTemplateParmExpr( 8548 ToType, E->getValueKind(), ToExprLoc, ToReplacement, ToAssociatedDecl, 8549 E->getIndex(), E->getPackIndex(), E->isReferenceParameter()); 8550 } 8551 8552 ExpectedStmt ASTNodeImporter::VisitTypeTraitExpr(TypeTraitExpr *E) { 8553 Error Err = Error::success(); 8554 auto ToType = importChecked(Err, E->getType()); 8555 auto ToBeginLoc = importChecked(Err, E->getBeginLoc()); 8556 auto ToEndLoc = importChecked(Err, E->getEndLoc()); 8557 if (Err) 8558 return std::move(Err); 8559 8560 SmallVector<TypeSourceInfo *, 4> ToArgs(E->getNumArgs()); 8561 if (Error Err = ImportContainerChecked(E->getArgs(), ToArgs)) 8562 return std::move(Err); 8563 8564 // According to Sema::BuildTypeTrait(), if E is value-dependent, 8565 // Value is always false. 8566 bool ToValue = (E->isValueDependent() ? false : E->getValue()); 8567 8568 return TypeTraitExpr::Create( 8569 Importer.getToContext(), ToType, ToBeginLoc, E->getTrait(), ToArgs, 8570 ToEndLoc, ToValue); 8571 } 8572 8573 ExpectedStmt ASTNodeImporter::VisitCXXTypeidExpr(CXXTypeidExpr *E) { 8574 ExpectedType ToTypeOrErr = import(E->getType()); 8575 if (!ToTypeOrErr) 8576 return ToTypeOrErr.takeError(); 8577 8578 auto ToSourceRangeOrErr = import(E->getSourceRange()); 8579 if (!ToSourceRangeOrErr) 8580 return ToSourceRangeOrErr.takeError(); 8581 8582 if (E->isTypeOperand()) { 8583 if (auto ToTSIOrErr = import(E->getTypeOperandSourceInfo())) 8584 return new (Importer.getToContext()) CXXTypeidExpr( 8585 *ToTypeOrErr, *ToTSIOrErr, *ToSourceRangeOrErr); 8586 else 8587 return ToTSIOrErr.takeError(); 8588 } 8589 8590 ExpectedExpr ToExprOperandOrErr = import(E->getExprOperand()); 8591 if (!ToExprOperandOrErr) 8592 return ToExprOperandOrErr.takeError(); 8593 8594 return new (Importer.getToContext()) CXXTypeidExpr( 8595 *ToTypeOrErr, *ToExprOperandOrErr, *ToSourceRangeOrErr); 8596 } 8597 8598 ExpectedStmt ASTNodeImporter::VisitCXXFoldExpr(CXXFoldExpr *E) { 8599 Error Err = Error::success(); 8600 8601 QualType ToType = importChecked(Err, E->getType()); 8602 UnresolvedLookupExpr *ToCallee = importChecked(Err, E->getCallee()); 8603 SourceLocation ToLParenLoc = importChecked(Err, E->getLParenLoc()); 8604 Expr *ToLHS = importChecked(Err, E->getLHS()); 8605 SourceLocation ToEllipsisLoc = importChecked(Err, E->getEllipsisLoc()); 8606 Expr *ToRHS = importChecked(Err, E->getRHS()); 8607 SourceLocation ToRParenLoc = importChecked(Err, E->getRParenLoc()); 8608 8609 if (Err) 8610 return std::move(Err); 8611 8612 return new (Importer.getToContext()) 8613 CXXFoldExpr(ToType, ToCallee, ToLParenLoc, ToLHS, E->getOperator(), 8614 ToEllipsisLoc, ToRHS, ToRParenLoc, E->getNumExpansions()); 8615 } 8616 8617 Error ASTNodeImporter::ImportOverriddenMethods(CXXMethodDecl *ToMethod, 8618 CXXMethodDecl *FromMethod) { 8619 Error ImportErrors = Error::success(); 8620 for (auto *FromOverriddenMethod : FromMethod->overridden_methods()) { 8621 if (auto ImportedOrErr = import(FromOverriddenMethod)) 8622 ToMethod->getCanonicalDecl()->addOverriddenMethod(cast<CXXMethodDecl>( 8623 (*ImportedOrErr)->getCanonicalDecl())); 8624 else 8625 ImportErrors = 8626 joinErrors(std::move(ImportErrors), ImportedOrErr.takeError()); 8627 } 8628 return ImportErrors; 8629 } 8630 8631 ASTImporter::ASTImporter(ASTContext &ToContext, FileManager &ToFileManager, 8632 ASTContext &FromContext, FileManager &FromFileManager, 8633 bool MinimalImport, 8634 std::shared_ptr<ASTImporterSharedState> SharedState) 8635 : SharedState(SharedState), ToContext(ToContext), FromContext(FromContext), 8636 ToFileManager(ToFileManager), FromFileManager(FromFileManager), 8637 Minimal(MinimalImport), ODRHandling(ODRHandlingType::Conservative) { 8638 8639 // Create a default state without the lookup table: LLDB case. 8640 if (!SharedState) { 8641 this->SharedState = std::make_shared<ASTImporterSharedState>(); 8642 } 8643 8644 ImportedDecls[FromContext.getTranslationUnitDecl()] = 8645 ToContext.getTranslationUnitDecl(); 8646 } 8647 8648 ASTImporter::~ASTImporter() = default; 8649 8650 std::optional<unsigned> ASTImporter::getFieldIndex(Decl *F) { 8651 assert(F && (isa<FieldDecl>(*F) || isa<IndirectFieldDecl>(*F)) && 8652 "Try to get field index for non-field."); 8653 8654 auto *Owner = dyn_cast<RecordDecl>(F->getDeclContext()); 8655 if (!Owner) 8656 return std::nullopt; 8657 8658 unsigned Index = 0; 8659 for (const auto *D : Owner->decls()) { 8660 if (D == F) 8661 return Index; 8662 8663 if (isa<FieldDecl>(*D) || isa<IndirectFieldDecl>(*D)) 8664 ++Index; 8665 } 8666 8667 llvm_unreachable("Field was not found in its parent context."); 8668 8669 return std::nullopt; 8670 } 8671 8672 ASTImporter::FoundDeclsTy 8673 ASTImporter::findDeclsInToCtx(DeclContext *DC, DeclarationName Name) { 8674 // We search in the redecl context because of transparent contexts. 8675 // E.g. a simple C language enum is a transparent context: 8676 // enum E { A, B }; 8677 // Now if we had a global variable in the TU 8678 // int A; 8679 // then the enum constant 'A' and the variable 'A' violates ODR. 8680 // We can diagnose this only if we search in the redecl context. 8681 DeclContext *ReDC = DC->getRedeclContext(); 8682 if (SharedState->getLookupTable()) { 8683 ASTImporterLookupTable::LookupResult LookupResult = 8684 SharedState->getLookupTable()->lookup(ReDC, Name); 8685 return FoundDeclsTy(LookupResult.begin(), LookupResult.end()); 8686 } else { 8687 DeclContext::lookup_result NoloadLookupResult = ReDC->noload_lookup(Name); 8688 FoundDeclsTy Result(NoloadLookupResult.begin(), NoloadLookupResult.end()); 8689 // We must search by the slow case of localUncachedLookup because that is 8690 // working even if there is no LookupPtr for the DC. We could use 8691 // DC::buildLookup() to create the LookupPtr, but that would load external 8692 // decls again, we must avoid that case. 8693 // Also, even if we had the LookupPtr, we must find Decls which are not 8694 // in the LookupPtr, so we need the slow case. 8695 // These cases are handled in ASTImporterLookupTable, but we cannot use 8696 // that with LLDB since that traverses through the AST which initiates the 8697 // load of external decls again via DC::decls(). And again, we must avoid 8698 // loading external decls during the import. 8699 if (Result.empty()) 8700 ReDC->localUncachedLookup(Name, Result); 8701 return Result; 8702 } 8703 } 8704 8705 void ASTImporter::AddToLookupTable(Decl *ToD) { 8706 SharedState->addDeclToLookup(ToD); 8707 } 8708 8709 Expected<Decl *> ASTImporter::ImportImpl(Decl *FromD) { 8710 // Import the decl using ASTNodeImporter. 8711 ASTNodeImporter Importer(*this); 8712 return Importer.Visit(FromD); 8713 } 8714 8715 void ASTImporter::RegisterImportedDecl(Decl *FromD, Decl *ToD) { 8716 MapImported(FromD, ToD); 8717 } 8718 8719 llvm::Expected<ExprWithCleanups::CleanupObject> 8720 ASTImporter::Import(ExprWithCleanups::CleanupObject From) { 8721 if (auto *CLE = From.dyn_cast<CompoundLiteralExpr *>()) { 8722 if (Expected<Expr *> R = Import(CLE)) 8723 return ExprWithCleanups::CleanupObject(cast<CompoundLiteralExpr>(*R)); 8724 } 8725 8726 // FIXME: Handle BlockDecl when we implement importing BlockExpr in 8727 // ASTNodeImporter. 8728 return make_error<ASTImportError>(ASTImportError::UnsupportedConstruct); 8729 } 8730 8731 ExpectedTypePtr ASTImporter::Import(const Type *FromT) { 8732 if (!FromT) 8733 return FromT; 8734 8735 // Check whether we've already imported this type. 8736 llvm::DenseMap<const Type *, const Type *>::iterator Pos = 8737 ImportedTypes.find(FromT); 8738 if (Pos != ImportedTypes.end()) 8739 return Pos->second; 8740 8741 // Import the type. 8742 ASTNodeImporter Importer(*this); 8743 ExpectedType ToTOrErr = Importer.Visit(FromT); 8744 if (!ToTOrErr) 8745 return ToTOrErr.takeError(); 8746 8747 // Record the imported type. 8748 ImportedTypes[FromT] = ToTOrErr->getTypePtr(); 8749 8750 return ToTOrErr->getTypePtr(); 8751 } 8752 8753 Expected<QualType> ASTImporter::Import(QualType FromT) { 8754 if (FromT.isNull()) 8755 return QualType{}; 8756 8757 ExpectedTypePtr ToTyOrErr = Import(FromT.getTypePtr()); 8758 if (!ToTyOrErr) 8759 return ToTyOrErr.takeError(); 8760 8761 return ToContext.getQualifiedType(*ToTyOrErr, FromT.getLocalQualifiers()); 8762 } 8763 8764 Expected<TypeSourceInfo *> ASTImporter::Import(TypeSourceInfo *FromTSI) { 8765 if (!FromTSI) 8766 return FromTSI; 8767 8768 // FIXME: For now we just create a "trivial" type source info based 8769 // on the type and a single location. Implement a real version of this. 8770 ExpectedType TOrErr = Import(FromTSI->getType()); 8771 if (!TOrErr) 8772 return TOrErr.takeError(); 8773 ExpectedSLoc BeginLocOrErr = Import(FromTSI->getTypeLoc().getBeginLoc()); 8774 if (!BeginLocOrErr) 8775 return BeginLocOrErr.takeError(); 8776 8777 return ToContext.getTrivialTypeSourceInfo(*TOrErr, *BeginLocOrErr); 8778 } 8779 8780 namespace { 8781 // To use this object, it should be created before the new attribute is created, 8782 // and destructed after it is created. The construction already performs the 8783 // import of the data. 8784 template <typename T> struct AttrArgImporter { 8785 AttrArgImporter(const AttrArgImporter<T> &) = delete; 8786 AttrArgImporter(AttrArgImporter<T> &&) = default; 8787 AttrArgImporter<T> &operator=(const AttrArgImporter<T> &) = delete; 8788 AttrArgImporter<T> &operator=(AttrArgImporter<T> &&) = default; 8789 8790 AttrArgImporter(ASTNodeImporter &I, Error &Err, const T &From) 8791 : To(I.importChecked(Err, From)) {} 8792 8793 const T &value() { return To; } 8794 8795 private: 8796 T To; 8797 }; 8798 8799 // To use this object, it should be created before the new attribute is created, 8800 // and destructed after it is created. The construction already performs the 8801 // import of the data. The array data is accessible in a pointer form, this form 8802 // is used by the attribute classes. This object should be created once for the 8803 // array data to be imported (the array size is not imported, just copied). 8804 template <typename T> struct AttrArgArrayImporter { 8805 AttrArgArrayImporter(const AttrArgArrayImporter<T> &) = delete; 8806 AttrArgArrayImporter(AttrArgArrayImporter<T> &&) = default; 8807 AttrArgArrayImporter<T> &operator=(const AttrArgArrayImporter<T> &) = delete; 8808 AttrArgArrayImporter<T> &operator=(AttrArgArrayImporter<T> &&) = default; 8809 8810 AttrArgArrayImporter(ASTNodeImporter &I, Error &Err, 8811 const llvm::iterator_range<T *> &From, 8812 unsigned ArraySize) { 8813 if (Err) 8814 return; 8815 To.reserve(ArraySize); 8816 Err = I.ImportContainerChecked(From, To); 8817 } 8818 8819 T *value() { return To.data(); } 8820 8821 private: 8822 llvm::SmallVector<T, 2> To; 8823 }; 8824 8825 class AttrImporter { 8826 Error Err{Error::success()}; 8827 Attr *ToAttr = nullptr; 8828 ASTImporter &Importer; 8829 ASTNodeImporter NImporter; 8830 8831 public: 8832 AttrImporter(ASTImporter &I) : Importer(I), NImporter(I) {} 8833 8834 // Create an "importer" for an attribute parameter. 8835 // Result of the 'value()' of that object is to be passed to the function 8836 // 'importAttr', in the order that is expected by the attribute class. 8837 template <class T> AttrArgImporter<T> importArg(const T &From) { 8838 return AttrArgImporter<T>(NImporter, Err, From); 8839 } 8840 8841 // Create an "importer" for an attribute parameter that has array type. 8842 // Result of the 'value()' of that object is to be passed to the function 8843 // 'importAttr', then the size of the array as next argument. 8844 template <typename T> 8845 AttrArgArrayImporter<T> importArrayArg(const llvm::iterator_range<T *> &From, 8846 unsigned ArraySize) { 8847 return AttrArgArrayImporter<T>(NImporter, Err, From, ArraySize); 8848 } 8849 8850 // Create an attribute object with the specified arguments. 8851 // The 'FromAttr' is the original (not imported) attribute, the 'ImportedArg' 8852 // should be values that are passed to the 'Create' function of the attribute. 8853 // (The 'Create' with 'ASTContext' first and 'AttributeCommonInfo' last is 8854 // used here.) As much data is copied or imported from the old attribute 8855 // as possible. The passed arguments should be already imported. 8856 // If an import error happens, the internal error is set to it, and any 8857 // further import attempt is ignored. 8858 template <typename T, typename... Arg> 8859 void importAttr(const T *FromAttr, Arg &&...ImportedArg) { 8860 static_assert(std::is_base_of<Attr, T>::value, 8861 "T should be subclass of Attr."); 8862 assert(!ToAttr && "Use one AttrImporter to import one Attribute object."); 8863 8864 const IdentifierInfo *ToAttrName = Importer.Import(FromAttr->getAttrName()); 8865 const IdentifierInfo *ToScopeName = 8866 Importer.Import(FromAttr->getScopeName()); 8867 SourceRange ToAttrRange = 8868 NImporter.importChecked(Err, FromAttr->getRange()); 8869 SourceLocation ToScopeLoc = 8870 NImporter.importChecked(Err, FromAttr->getScopeLoc()); 8871 8872 if (Err) 8873 return; 8874 8875 AttributeCommonInfo ToI(ToAttrName, ToScopeName, ToAttrRange, ToScopeLoc, 8876 FromAttr->getParsedKind(), FromAttr->getForm()); 8877 // The "SemanticSpelling" is not needed to be passed to the constructor. 8878 // That value is recalculated from the SpellingListIndex if needed. 8879 ToAttr = T::Create(Importer.getToContext(), 8880 std::forward<Arg>(ImportedArg)..., ToI); 8881 8882 ToAttr->setImplicit(FromAttr->isImplicit()); 8883 ToAttr->setPackExpansion(FromAttr->isPackExpansion()); 8884 if (auto *ToInheritableAttr = dyn_cast<InheritableAttr>(ToAttr)) 8885 ToInheritableAttr->setInherited(FromAttr->isInherited()); 8886 } 8887 8888 // Create a clone of the 'FromAttr' and import its source range only. 8889 // This causes objects with invalid references to be created if the 'FromAttr' 8890 // contains other data that should be imported. 8891 void cloneAttr(const Attr *FromAttr) { 8892 assert(!ToAttr && "Use one AttrImporter to import one Attribute object."); 8893 8894 SourceRange ToRange = NImporter.importChecked(Err, FromAttr->getRange()); 8895 if (Err) 8896 return; 8897 8898 ToAttr = FromAttr->clone(Importer.getToContext()); 8899 ToAttr->setRange(ToRange); 8900 } 8901 8902 // Get the result of the previous import attempt (can be used only once). 8903 llvm::Expected<Attr *> getResult() && { 8904 if (Err) 8905 return std::move(Err); 8906 assert(ToAttr && "Attribute should be created."); 8907 return ToAttr; 8908 } 8909 }; 8910 } // namespace 8911 8912 Expected<Attr *> ASTImporter::Import(const Attr *FromAttr) { 8913 AttrImporter AI(*this); 8914 8915 // FIXME: Is there some kind of AttrVisitor to use here? 8916 switch (FromAttr->getKind()) { 8917 case attr::Aligned: { 8918 auto *From = cast<AlignedAttr>(FromAttr); 8919 if (From->isAlignmentExpr()) 8920 AI.importAttr(From, true, AI.importArg(From->getAlignmentExpr()).value()); 8921 else 8922 AI.importAttr(From, false, 8923 AI.importArg(From->getAlignmentType()).value()); 8924 break; 8925 } 8926 8927 case attr::Format: { 8928 const auto *From = cast<FormatAttr>(FromAttr); 8929 AI.importAttr(From, Import(From->getType()), From->getFormatIdx(), 8930 From->getFirstArg()); 8931 break; 8932 } 8933 8934 case attr::EnableIf: { 8935 const auto *From = cast<EnableIfAttr>(FromAttr); 8936 AI.importAttr(From, AI.importArg(From->getCond()).value(), 8937 From->getMessage()); 8938 break; 8939 } 8940 8941 case attr::AssertCapability: { 8942 const auto *From = cast<AssertCapabilityAttr>(FromAttr); 8943 AI.importAttr(From, 8944 AI.importArrayArg(From->args(), From->args_size()).value(), 8945 From->args_size()); 8946 break; 8947 } 8948 case attr::AcquireCapability: { 8949 const auto *From = cast<AcquireCapabilityAttr>(FromAttr); 8950 AI.importAttr(From, 8951 AI.importArrayArg(From->args(), From->args_size()).value(), 8952 From->args_size()); 8953 break; 8954 } 8955 case attr::TryAcquireCapability: { 8956 const auto *From = cast<TryAcquireCapabilityAttr>(FromAttr); 8957 AI.importAttr(From, AI.importArg(From->getSuccessValue()).value(), 8958 AI.importArrayArg(From->args(), From->args_size()).value(), 8959 From->args_size()); 8960 break; 8961 } 8962 case attr::ReleaseCapability: { 8963 const auto *From = cast<ReleaseCapabilityAttr>(FromAttr); 8964 AI.importAttr(From, 8965 AI.importArrayArg(From->args(), From->args_size()).value(), 8966 From->args_size()); 8967 break; 8968 } 8969 case attr::RequiresCapability: { 8970 const auto *From = cast<RequiresCapabilityAttr>(FromAttr); 8971 AI.importAttr(From, 8972 AI.importArrayArg(From->args(), From->args_size()).value(), 8973 From->args_size()); 8974 break; 8975 } 8976 case attr::GuardedBy: { 8977 const auto *From = cast<GuardedByAttr>(FromAttr); 8978 AI.importAttr(From, AI.importArg(From->getArg()).value()); 8979 break; 8980 } 8981 case attr::PtGuardedBy: { 8982 const auto *From = cast<PtGuardedByAttr>(FromAttr); 8983 AI.importAttr(From, AI.importArg(From->getArg()).value()); 8984 break; 8985 } 8986 case attr::AcquiredAfter: { 8987 const auto *From = cast<AcquiredAfterAttr>(FromAttr); 8988 AI.importAttr(From, 8989 AI.importArrayArg(From->args(), From->args_size()).value(), 8990 From->args_size()); 8991 break; 8992 } 8993 case attr::AcquiredBefore: { 8994 const auto *From = cast<AcquiredBeforeAttr>(FromAttr); 8995 AI.importAttr(From, 8996 AI.importArrayArg(From->args(), From->args_size()).value(), 8997 From->args_size()); 8998 break; 8999 } 9000 case attr::AssertExclusiveLock: { 9001 const auto *From = cast<AssertExclusiveLockAttr>(FromAttr); 9002 AI.importAttr(From, 9003 AI.importArrayArg(From->args(), From->args_size()).value(), 9004 From->args_size()); 9005 break; 9006 } 9007 case attr::AssertSharedLock: { 9008 const auto *From = cast<AssertSharedLockAttr>(FromAttr); 9009 AI.importAttr(From, 9010 AI.importArrayArg(From->args(), From->args_size()).value(), 9011 From->args_size()); 9012 break; 9013 } 9014 case attr::ExclusiveTrylockFunction: { 9015 const auto *From = cast<ExclusiveTrylockFunctionAttr>(FromAttr); 9016 AI.importAttr(From, AI.importArg(From->getSuccessValue()).value(), 9017 AI.importArrayArg(From->args(), From->args_size()).value(), 9018 From->args_size()); 9019 break; 9020 } 9021 case attr::SharedTrylockFunction: { 9022 const auto *From = cast<SharedTrylockFunctionAttr>(FromAttr); 9023 AI.importAttr(From, AI.importArg(From->getSuccessValue()).value(), 9024 AI.importArrayArg(From->args(), From->args_size()).value(), 9025 From->args_size()); 9026 break; 9027 } 9028 case attr::LockReturned: { 9029 const auto *From = cast<LockReturnedAttr>(FromAttr); 9030 AI.importAttr(From, AI.importArg(From->getArg()).value()); 9031 break; 9032 } 9033 case attr::LocksExcluded: { 9034 const auto *From = cast<LocksExcludedAttr>(FromAttr); 9035 AI.importAttr(From, 9036 AI.importArrayArg(From->args(), From->args_size()).value(), 9037 From->args_size()); 9038 break; 9039 } 9040 9041 default: { 9042 // The default branch works for attributes that have no arguments to import. 9043 // FIXME: Handle every attribute type that has arguments of type to import 9044 // (most often Expr* or Decl* or type) in the switch above. 9045 AI.cloneAttr(FromAttr); 9046 break; 9047 } 9048 } 9049 9050 return std::move(AI).getResult(); 9051 } 9052 9053 Decl *ASTImporter::GetAlreadyImportedOrNull(const Decl *FromD) const { 9054 return ImportedDecls.lookup(FromD); 9055 } 9056 9057 TranslationUnitDecl *ASTImporter::GetFromTU(Decl *ToD) { 9058 auto FromDPos = ImportedFromDecls.find(ToD); 9059 if (FromDPos == ImportedFromDecls.end()) 9060 return nullptr; 9061 return FromDPos->second->getTranslationUnitDecl(); 9062 } 9063 9064 Error ASTImporter::ImportAttrs(Decl *ToD, Decl *FromD) { 9065 if (!FromD->hasAttrs() || ToD->hasAttrs()) 9066 return Error::success(); 9067 for (const Attr *FromAttr : FromD->getAttrs()) { 9068 auto ToAttrOrErr = Import(FromAttr); 9069 if (ToAttrOrErr) 9070 ToD->addAttr(*ToAttrOrErr); 9071 else 9072 return ToAttrOrErr.takeError(); 9073 } 9074 return Error::success(); 9075 } 9076 9077 Expected<Decl *> ASTImporter::Import(Decl *FromD) { 9078 if (!FromD) 9079 return nullptr; 9080 9081 // Push FromD to the stack, and remove that when we return. 9082 ImportPath.push(FromD); 9083 auto ImportPathBuilder = 9084 llvm::make_scope_exit([this]() { ImportPath.pop(); }); 9085 9086 // Check whether there was a previous failed import. 9087 // If yes return the existing error. 9088 if (auto Error = getImportDeclErrorIfAny(FromD)) 9089 return make_error<ASTImportError>(*Error); 9090 9091 // Check whether we've already imported this declaration. 9092 Decl *ToD = GetAlreadyImportedOrNull(FromD); 9093 if (ToD) { 9094 // Already imported (possibly from another TU) and with an error. 9095 if (auto Error = SharedState->getImportDeclErrorIfAny(ToD)) { 9096 setImportDeclError(FromD, *Error); 9097 return make_error<ASTImportError>(*Error); 9098 } 9099 9100 // If FromD has some updated flags after last import, apply it. 9101 updateFlags(FromD, ToD); 9102 // If we encounter a cycle during an import then we save the relevant part 9103 // of the import path associated to the Decl. 9104 if (ImportPath.hasCycleAtBack()) 9105 SavedImportPaths[FromD].push_back(ImportPath.copyCycleAtBack()); 9106 return ToD; 9107 } 9108 9109 // Import the declaration. 9110 ExpectedDecl ToDOrErr = ImportImpl(FromD); 9111 if (!ToDOrErr) { 9112 // Failed to import. 9113 9114 auto Pos = ImportedDecls.find(FromD); 9115 if (Pos != ImportedDecls.end()) { 9116 // Import failed after the object was created. 9117 // Remove all references to it. 9118 auto *ToD = Pos->second; 9119 ImportedDecls.erase(Pos); 9120 9121 // ImportedDecls and ImportedFromDecls are not symmetric. It may happen 9122 // (e.g. with namespaces) that several decls from the 'from' context are 9123 // mapped to the same decl in the 'to' context. If we removed entries 9124 // from the LookupTable here then we may end up removing them multiple 9125 // times. 9126 9127 // The Lookuptable contains decls only which are in the 'to' context. 9128 // Remove from the Lookuptable only if it is *imported* into the 'to' 9129 // context (and do not remove it if it was added during the initial 9130 // traverse of the 'to' context). 9131 auto PosF = ImportedFromDecls.find(ToD); 9132 if (PosF != ImportedFromDecls.end()) { 9133 // In the case of TypedefNameDecl we create the Decl first and only 9134 // then we import and set its DeclContext. So, the DC might not be set 9135 // when we reach here. 9136 if (ToD->getDeclContext()) 9137 SharedState->removeDeclFromLookup(ToD); 9138 ImportedFromDecls.erase(PosF); 9139 } 9140 9141 // FIXME: AST may contain remaining references to the failed object. 9142 // However, the ImportDeclErrors in the shared state contains all the 9143 // failed objects together with their error. 9144 } 9145 9146 // Error encountered for the first time. 9147 // After takeError the error is not usable any more in ToDOrErr. 9148 // Get a copy of the error object (any more simple solution for this?). 9149 ASTImportError ErrOut; 9150 handleAllErrors(ToDOrErr.takeError(), 9151 [&ErrOut](const ASTImportError &E) { ErrOut = E; }); 9152 setImportDeclError(FromD, ErrOut); 9153 // Set the error for the mapped to Decl, which is in the "to" context. 9154 if (Pos != ImportedDecls.end()) 9155 SharedState->setImportDeclError(Pos->second, ErrOut); 9156 9157 // Set the error for all nodes which have been created before we 9158 // recognized the error. 9159 for (const auto &Path : SavedImportPaths[FromD]) { 9160 // The import path contains import-dependency nodes first. 9161 // Save the node that was imported as dependency of the current node. 9162 Decl *PrevFromDi = FromD; 9163 for (Decl *FromDi : Path) { 9164 // Begin and end of the path equals 'FromD', skip it. 9165 if (FromDi == FromD) 9166 continue; 9167 // We should not set import error on a node and all following nodes in 9168 // the path if child import errors are ignored. 9169 if (ChildErrorHandlingStrategy(FromDi).ignoreChildErrorOnParent( 9170 PrevFromDi)) 9171 break; 9172 PrevFromDi = FromDi; 9173 setImportDeclError(FromDi, ErrOut); 9174 //FIXME Should we remove these Decls from ImportedDecls? 9175 // Set the error for the mapped to Decl, which is in the "to" context. 9176 auto Ii = ImportedDecls.find(FromDi); 9177 if (Ii != ImportedDecls.end()) 9178 SharedState->setImportDeclError(Ii->second, ErrOut); 9179 // FIXME Should we remove these Decls from the LookupTable, 9180 // and from ImportedFromDecls? 9181 } 9182 } 9183 SavedImportPaths.erase(FromD); 9184 9185 // Do not return ToDOrErr, error was taken out of it. 9186 return make_error<ASTImportError>(ErrOut); 9187 } 9188 9189 ToD = *ToDOrErr; 9190 9191 // FIXME: Handle the "already imported with error" case. We can get here 9192 // nullptr only if GetImportedOrCreateDecl returned nullptr (after a 9193 // previously failed create was requested). 9194 // Later GetImportedOrCreateDecl can be updated to return the error. 9195 if (!ToD) { 9196 auto Err = getImportDeclErrorIfAny(FromD); 9197 assert(Err); 9198 return make_error<ASTImportError>(*Err); 9199 } 9200 9201 // We could import from the current TU without error. But previously we 9202 // already had imported a Decl as `ToD` from another TU (with another 9203 // ASTImporter object) and with an error. 9204 if (auto Error = SharedState->getImportDeclErrorIfAny(ToD)) { 9205 setImportDeclError(FromD, *Error); 9206 return make_error<ASTImportError>(*Error); 9207 } 9208 9209 // Make sure that ImportImpl registered the imported decl. 9210 assert(ImportedDecls.count(FromD) != 0 && "Missing call to MapImported?"); 9211 if (auto Error = ImportAttrs(ToD, FromD)) 9212 return std::move(Error); 9213 9214 // Notify subclasses. 9215 Imported(FromD, ToD); 9216 9217 updateFlags(FromD, ToD); 9218 SavedImportPaths.erase(FromD); 9219 return ToDOrErr; 9220 } 9221 9222 llvm::Expected<InheritedConstructor> 9223 ASTImporter::Import(const InheritedConstructor &From) { 9224 return ASTNodeImporter(*this).ImportInheritedConstructor(From); 9225 } 9226 9227 Expected<DeclContext *> ASTImporter::ImportContext(DeclContext *FromDC) { 9228 if (!FromDC) 9229 return FromDC; 9230 9231 ExpectedDecl ToDCOrErr = Import(cast<Decl>(FromDC)); 9232 if (!ToDCOrErr) 9233 return ToDCOrErr.takeError(); 9234 auto *ToDC = cast<DeclContext>(*ToDCOrErr); 9235 9236 // When we're using a record/enum/Objective-C class/protocol as a context, we 9237 // need it to have a definition. 9238 if (auto *ToRecord = dyn_cast<RecordDecl>(ToDC)) { 9239 auto *FromRecord = cast<RecordDecl>(FromDC); 9240 if (ToRecord->isCompleteDefinition()) 9241 return ToDC; 9242 9243 // If FromRecord is not defined we need to force it to be. 9244 // Simply calling CompleteDecl(...) for a RecordDecl will break some cases 9245 // it will start the definition but we never finish it. 9246 // If there are base classes they won't be imported and we will 9247 // be missing anything that we inherit from those bases. 9248 if (FromRecord->getASTContext().getExternalSource() && 9249 !FromRecord->isCompleteDefinition()) 9250 FromRecord->getASTContext().getExternalSource()->CompleteType(FromRecord); 9251 9252 if (FromRecord->isCompleteDefinition()) 9253 if (Error Err = ASTNodeImporter(*this).ImportDefinition( 9254 FromRecord, ToRecord, ASTNodeImporter::IDK_Basic)) 9255 return std::move(Err); 9256 } else if (auto *ToEnum = dyn_cast<EnumDecl>(ToDC)) { 9257 auto *FromEnum = cast<EnumDecl>(FromDC); 9258 if (ToEnum->isCompleteDefinition()) { 9259 // Do nothing. 9260 } else if (FromEnum->isCompleteDefinition()) { 9261 if (Error Err = ASTNodeImporter(*this).ImportDefinition( 9262 FromEnum, ToEnum, ASTNodeImporter::IDK_Basic)) 9263 return std::move(Err); 9264 } else { 9265 CompleteDecl(ToEnum); 9266 } 9267 } else if (auto *ToClass = dyn_cast<ObjCInterfaceDecl>(ToDC)) { 9268 auto *FromClass = cast<ObjCInterfaceDecl>(FromDC); 9269 if (ToClass->getDefinition()) { 9270 // Do nothing. 9271 } else if (ObjCInterfaceDecl *FromDef = FromClass->getDefinition()) { 9272 if (Error Err = ASTNodeImporter(*this).ImportDefinition( 9273 FromDef, ToClass, ASTNodeImporter::IDK_Basic)) 9274 return std::move(Err); 9275 } else { 9276 CompleteDecl(ToClass); 9277 } 9278 } else if (auto *ToProto = dyn_cast<ObjCProtocolDecl>(ToDC)) { 9279 auto *FromProto = cast<ObjCProtocolDecl>(FromDC); 9280 if (ToProto->getDefinition()) { 9281 // Do nothing. 9282 } else if (ObjCProtocolDecl *FromDef = FromProto->getDefinition()) { 9283 if (Error Err = ASTNodeImporter(*this).ImportDefinition( 9284 FromDef, ToProto, ASTNodeImporter::IDK_Basic)) 9285 return std::move(Err); 9286 } else { 9287 CompleteDecl(ToProto); 9288 } 9289 } 9290 9291 return ToDC; 9292 } 9293 9294 Expected<Expr *> ASTImporter::Import(Expr *FromE) { 9295 if (ExpectedStmt ToSOrErr = Import(cast_or_null<Stmt>(FromE))) 9296 return cast_or_null<Expr>(*ToSOrErr); 9297 else 9298 return ToSOrErr.takeError(); 9299 } 9300 9301 Expected<Stmt *> ASTImporter::Import(Stmt *FromS) { 9302 if (!FromS) 9303 return nullptr; 9304 9305 // Check whether we've already imported this statement. 9306 llvm::DenseMap<Stmt *, Stmt *>::iterator Pos = ImportedStmts.find(FromS); 9307 if (Pos != ImportedStmts.end()) 9308 return Pos->second; 9309 9310 // Import the statement. 9311 ASTNodeImporter Importer(*this); 9312 ExpectedStmt ToSOrErr = Importer.Visit(FromS); 9313 if (!ToSOrErr) 9314 return ToSOrErr; 9315 9316 if (auto *ToE = dyn_cast<Expr>(*ToSOrErr)) { 9317 auto *FromE = cast<Expr>(FromS); 9318 // Copy ExprBitfields, which may not be handled in Expr subclasses 9319 // constructors. 9320 ToE->setValueKind(FromE->getValueKind()); 9321 ToE->setObjectKind(FromE->getObjectKind()); 9322 ToE->setDependence(FromE->getDependence()); 9323 } 9324 9325 // Record the imported statement object. 9326 ImportedStmts[FromS] = *ToSOrErr; 9327 return ToSOrErr; 9328 } 9329 9330 Expected<NestedNameSpecifier *> 9331 ASTImporter::Import(NestedNameSpecifier *FromNNS) { 9332 if (!FromNNS) 9333 return nullptr; 9334 9335 NestedNameSpecifier *Prefix = nullptr; 9336 if (Error Err = importInto(Prefix, FromNNS->getPrefix())) 9337 return std::move(Err); 9338 9339 switch (FromNNS->getKind()) { 9340 case NestedNameSpecifier::Identifier: 9341 assert(FromNNS->getAsIdentifier() && "NNS should contain identifier."); 9342 return NestedNameSpecifier::Create(ToContext, Prefix, 9343 Import(FromNNS->getAsIdentifier())); 9344 9345 case NestedNameSpecifier::Namespace: 9346 if (ExpectedDecl NSOrErr = Import(FromNNS->getAsNamespace())) { 9347 return NestedNameSpecifier::Create(ToContext, Prefix, 9348 cast<NamespaceDecl>(*NSOrErr)); 9349 } else 9350 return NSOrErr.takeError(); 9351 9352 case NestedNameSpecifier::NamespaceAlias: 9353 if (ExpectedDecl NSADOrErr = Import(FromNNS->getAsNamespaceAlias())) 9354 return NestedNameSpecifier::Create(ToContext, Prefix, 9355 cast<NamespaceAliasDecl>(*NSADOrErr)); 9356 else 9357 return NSADOrErr.takeError(); 9358 9359 case NestedNameSpecifier::Global: 9360 return NestedNameSpecifier::GlobalSpecifier(ToContext); 9361 9362 case NestedNameSpecifier::Super: 9363 if (ExpectedDecl RDOrErr = Import(FromNNS->getAsRecordDecl())) 9364 return NestedNameSpecifier::SuperSpecifier(ToContext, 9365 cast<CXXRecordDecl>(*RDOrErr)); 9366 else 9367 return RDOrErr.takeError(); 9368 9369 case NestedNameSpecifier::TypeSpec: 9370 case NestedNameSpecifier::TypeSpecWithTemplate: 9371 if (ExpectedTypePtr TyOrErr = Import(FromNNS->getAsType())) { 9372 bool TSTemplate = 9373 FromNNS->getKind() == NestedNameSpecifier::TypeSpecWithTemplate; 9374 return NestedNameSpecifier::Create(ToContext, Prefix, TSTemplate, 9375 *TyOrErr); 9376 } else { 9377 return TyOrErr.takeError(); 9378 } 9379 } 9380 9381 llvm_unreachable("Invalid nested name specifier kind"); 9382 } 9383 9384 Expected<NestedNameSpecifierLoc> 9385 ASTImporter::Import(NestedNameSpecifierLoc FromNNS) { 9386 // Copied from NestedNameSpecifier mostly. 9387 SmallVector<NestedNameSpecifierLoc , 8> NestedNames; 9388 NestedNameSpecifierLoc NNS = FromNNS; 9389 9390 // Push each of the nested-name-specifiers's onto a stack for 9391 // serialization in reverse order. 9392 while (NNS) { 9393 NestedNames.push_back(NNS); 9394 NNS = NNS.getPrefix(); 9395 } 9396 9397 NestedNameSpecifierLocBuilder Builder; 9398 9399 while (!NestedNames.empty()) { 9400 NNS = NestedNames.pop_back_val(); 9401 NestedNameSpecifier *Spec = nullptr; 9402 if (Error Err = importInto(Spec, NNS.getNestedNameSpecifier())) 9403 return std::move(Err); 9404 9405 NestedNameSpecifier::SpecifierKind Kind = Spec->getKind(); 9406 9407 SourceLocation ToLocalBeginLoc, ToLocalEndLoc; 9408 if (Kind != NestedNameSpecifier::Super) { 9409 if (Error Err = importInto(ToLocalBeginLoc, NNS.getLocalBeginLoc())) 9410 return std::move(Err); 9411 9412 if (Kind != NestedNameSpecifier::Global) 9413 if (Error Err = importInto(ToLocalEndLoc, NNS.getLocalEndLoc())) 9414 return std::move(Err); 9415 } 9416 9417 switch (Kind) { 9418 case NestedNameSpecifier::Identifier: 9419 Builder.Extend(getToContext(), Spec->getAsIdentifier(), ToLocalBeginLoc, 9420 ToLocalEndLoc); 9421 break; 9422 9423 case NestedNameSpecifier::Namespace: 9424 Builder.Extend(getToContext(), Spec->getAsNamespace(), ToLocalBeginLoc, 9425 ToLocalEndLoc); 9426 break; 9427 9428 case NestedNameSpecifier::NamespaceAlias: 9429 Builder.Extend(getToContext(), Spec->getAsNamespaceAlias(), 9430 ToLocalBeginLoc, ToLocalEndLoc); 9431 break; 9432 9433 case NestedNameSpecifier::TypeSpec: 9434 case NestedNameSpecifier::TypeSpecWithTemplate: { 9435 SourceLocation ToTLoc; 9436 if (Error Err = importInto(ToTLoc, NNS.getTypeLoc().getBeginLoc())) 9437 return std::move(Err); 9438 TypeSourceInfo *TSI = getToContext().getTrivialTypeSourceInfo( 9439 QualType(Spec->getAsType(), 0), ToTLoc); 9440 if (Kind == NestedNameSpecifier::TypeSpecWithTemplate) 9441 // ToLocalBeginLoc is here the location of the 'template' keyword. 9442 Builder.Extend(getToContext(), ToLocalBeginLoc, TSI->getTypeLoc(), 9443 ToLocalEndLoc); 9444 else 9445 // No location for 'template' keyword here. 9446 Builder.Extend(getToContext(), SourceLocation{}, TSI->getTypeLoc(), 9447 ToLocalEndLoc); 9448 break; 9449 } 9450 9451 case NestedNameSpecifier::Global: 9452 Builder.MakeGlobal(getToContext(), ToLocalBeginLoc); 9453 break; 9454 9455 case NestedNameSpecifier::Super: { 9456 auto ToSourceRangeOrErr = Import(NNS.getSourceRange()); 9457 if (!ToSourceRangeOrErr) 9458 return ToSourceRangeOrErr.takeError(); 9459 9460 Builder.MakeSuper(getToContext(), Spec->getAsRecordDecl(), 9461 ToSourceRangeOrErr->getBegin(), 9462 ToSourceRangeOrErr->getEnd()); 9463 } 9464 } 9465 } 9466 9467 return Builder.getWithLocInContext(getToContext()); 9468 } 9469 9470 Expected<TemplateName> ASTImporter::Import(TemplateName From) { 9471 switch (From.getKind()) { 9472 case TemplateName::Template: 9473 if (ExpectedDecl ToTemplateOrErr = Import(From.getAsTemplateDecl())) 9474 return TemplateName(cast<TemplateDecl>((*ToTemplateOrErr)->getCanonicalDecl())); 9475 else 9476 return ToTemplateOrErr.takeError(); 9477 9478 case TemplateName::OverloadedTemplate: { 9479 OverloadedTemplateStorage *FromStorage = From.getAsOverloadedTemplate(); 9480 UnresolvedSet<2> ToTemplates; 9481 for (auto *I : *FromStorage) { 9482 if (auto ToOrErr = Import(I)) 9483 ToTemplates.addDecl(cast<NamedDecl>(*ToOrErr)); 9484 else 9485 return ToOrErr.takeError(); 9486 } 9487 return ToContext.getOverloadedTemplateName(ToTemplates.begin(), 9488 ToTemplates.end()); 9489 } 9490 9491 case TemplateName::AssumedTemplate: { 9492 AssumedTemplateStorage *FromStorage = From.getAsAssumedTemplateName(); 9493 auto DeclNameOrErr = Import(FromStorage->getDeclName()); 9494 if (!DeclNameOrErr) 9495 return DeclNameOrErr.takeError(); 9496 return ToContext.getAssumedTemplateName(*DeclNameOrErr); 9497 } 9498 9499 case TemplateName::QualifiedTemplate: { 9500 QualifiedTemplateName *QTN = From.getAsQualifiedTemplateName(); 9501 auto QualifierOrErr = Import(QTN->getQualifier()); 9502 if (!QualifierOrErr) 9503 return QualifierOrErr.takeError(); 9504 auto TNOrErr = Import(QTN->getUnderlyingTemplate()); 9505 if (!TNOrErr) 9506 return TNOrErr.takeError(); 9507 return ToContext.getQualifiedTemplateName( 9508 *QualifierOrErr, QTN->hasTemplateKeyword(), *TNOrErr); 9509 } 9510 9511 case TemplateName::DependentTemplate: { 9512 DependentTemplateName *DTN = From.getAsDependentTemplateName(); 9513 auto QualifierOrErr = Import(DTN->getQualifier()); 9514 if (!QualifierOrErr) 9515 return QualifierOrErr.takeError(); 9516 9517 if (DTN->isIdentifier()) { 9518 return ToContext.getDependentTemplateName(*QualifierOrErr, 9519 Import(DTN->getIdentifier())); 9520 } 9521 9522 return ToContext.getDependentTemplateName(*QualifierOrErr, 9523 DTN->getOperator()); 9524 } 9525 9526 case TemplateName::SubstTemplateTemplateParm: { 9527 SubstTemplateTemplateParmStorage *Subst = 9528 From.getAsSubstTemplateTemplateParm(); 9529 auto ReplacementOrErr = Import(Subst->getReplacement()); 9530 if (!ReplacementOrErr) 9531 return ReplacementOrErr.takeError(); 9532 9533 auto AssociatedDeclOrErr = Import(Subst->getAssociatedDecl()); 9534 if (!AssociatedDeclOrErr) 9535 return AssociatedDeclOrErr.takeError(); 9536 9537 return ToContext.getSubstTemplateTemplateParm( 9538 *ReplacementOrErr, *AssociatedDeclOrErr, Subst->getIndex(), 9539 Subst->getPackIndex()); 9540 } 9541 9542 case TemplateName::SubstTemplateTemplateParmPack: { 9543 SubstTemplateTemplateParmPackStorage *SubstPack = 9544 From.getAsSubstTemplateTemplateParmPack(); 9545 ASTNodeImporter Importer(*this); 9546 auto ArgPackOrErr = 9547 Importer.ImportTemplateArgument(SubstPack->getArgumentPack()); 9548 if (!ArgPackOrErr) 9549 return ArgPackOrErr.takeError(); 9550 9551 auto AssociatedDeclOrErr = Import(SubstPack->getAssociatedDecl()); 9552 if (!AssociatedDeclOrErr) 9553 return AssociatedDeclOrErr.takeError(); 9554 9555 return ToContext.getSubstTemplateTemplateParmPack( 9556 *ArgPackOrErr, *AssociatedDeclOrErr, SubstPack->getIndex(), 9557 SubstPack->getFinal()); 9558 } 9559 case TemplateName::UsingTemplate: { 9560 auto UsingOrError = Import(From.getAsUsingShadowDecl()); 9561 if (!UsingOrError) 9562 return UsingOrError.takeError(); 9563 return TemplateName(cast<UsingShadowDecl>(*UsingOrError)); 9564 } 9565 } 9566 9567 llvm_unreachable("Invalid template name kind"); 9568 } 9569 9570 Expected<SourceLocation> ASTImporter::Import(SourceLocation FromLoc) { 9571 if (FromLoc.isInvalid()) 9572 return SourceLocation{}; 9573 9574 SourceManager &FromSM = FromContext.getSourceManager(); 9575 bool IsBuiltin = FromSM.isWrittenInBuiltinFile(FromLoc); 9576 9577 std::pair<FileID, unsigned> Decomposed = FromSM.getDecomposedLoc(FromLoc); 9578 Expected<FileID> ToFileIDOrErr = Import(Decomposed.first, IsBuiltin); 9579 if (!ToFileIDOrErr) 9580 return ToFileIDOrErr.takeError(); 9581 SourceManager &ToSM = ToContext.getSourceManager(); 9582 return ToSM.getComposedLoc(*ToFileIDOrErr, Decomposed.second); 9583 } 9584 9585 Expected<SourceRange> ASTImporter::Import(SourceRange FromRange) { 9586 SourceLocation ToBegin, ToEnd; 9587 if (Error Err = importInto(ToBegin, FromRange.getBegin())) 9588 return std::move(Err); 9589 if (Error Err = importInto(ToEnd, FromRange.getEnd())) 9590 return std::move(Err); 9591 9592 return SourceRange(ToBegin, ToEnd); 9593 } 9594 9595 Expected<FileID> ASTImporter::Import(FileID FromID, bool IsBuiltin) { 9596 llvm::DenseMap<FileID, FileID>::iterator Pos = ImportedFileIDs.find(FromID); 9597 if (Pos != ImportedFileIDs.end()) 9598 return Pos->second; 9599 9600 SourceManager &FromSM = FromContext.getSourceManager(); 9601 SourceManager &ToSM = ToContext.getSourceManager(); 9602 const SrcMgr::SLocEntry &FromSLoc = FromSM.getSLocEntry(FromID); 9603 9604 // Map the FromID to the "to" source manager. 9605 FileID ToID; 9606 if (FromSLoc.isExpansion()) { 9607 const SrcMgr::ExpansionInfo &FromEx = FromSLoc.getExpansion(); 9608 ExpectedSLoc ToSpLoc = Import(FromEx.getSpellingLoc()); 9609 if (!ToSpLoc) 9610 return ToSpLoc.takeError(); 9611 ExpectedSLoc ToExLocS = Import(FromEx.getExpansionLocStart()); 9612 if (!ToExLocS) 9613 return ToExLocS.takeError(); 9614 unsigned ExLength = FromSM.getFileIDSize(FromID); 9615 SourceLocation MLoc; 9616 if (FromEx.isMacroArgExpansion()) { 9617 MLoc = ToSM.createMacroArgExpansionLoc(*ToSpLoc, *ToExLocS, ExLength); 9618 } else { 9619 if (ExpectedSLoc ToExLocE = Import(FromEx.getExpansionLocEnd())) 9620 MLoc = ToSM.createExpansionLoc(*ToSpLoc, *ToExLocS, *ToExLocE, ExLength, 9621 FromEx.isExpansionTokenRange()); 9622 else 9623 return ToExLocE.takeError(); 9624 } 9625 ToID = ToSM.getFileID(MLoc); 9626 } else { 9627 const SrcMgr::ContentCache *Cache = &FromSLoc.getFile().getContentCache(); 9628 9629 if (!IsBuiltin && !Cache->BufferOverridden) { 9630 // Include location of this file. 9631 ExpectedSLoc ToIncludeLoc = Import(FromSLoc.getFile().getIncludeLoc()); 9632 if (!ToIncludeLoc) 9633 return ToIncludeLoc.takeError(); 9634 9635 // Every FileID that is not the main FileID needs to have a valid include 9636 // location so that the include chain points to the main FileID. When 9637 // importing the main FileID (which has no include location), we need to 9638 // create a fake include location in the main file to keep this property 9639 // intact. 9640 SourceLocation ToIncludeLocOrFakeLoc = *ToIncludeLoc; 9641 if (FromID == FromSM.getMainFileID()) 9642 ToIncludeLocOrFakeLoc = ToSM.getLocForStartOfFile(ToSM.getMainFileID()); 9643 9644 if (Cache->OrigEntry && Cache->OrigEntry->getDir()) { 9645 // FIXME: We probably want to use getVirtualFile(), so we don't hit the 9646 // disk again 9647 // FIXME: We definitely want to re-use the existing MemoryBuffer, rather 9648 // than mmap the files several times. 9649 auto Entry = 9650 ToFileManager.getOptionalFileRef(Cache->OrigEntry->getName()); 9651 // FIXME: The filename may be a virtual name that does probably not 9652 // point to a valid file and we get no Entry here. In this case try with 9653 // the memory buffer below. 9654 if (Entry) 9655 ToID = ToSM.createFileID(*Entry, ToIncludeLocOrFakeLoc, 9656 FromSLoc.getFile().getFileCharacteristic()); 9657 } 9658 } 9659 9660 if (ToID.isInvalid() || IsBuiltin) { 9661 // FIXME: We want to re-use the existing MemoryBuffer! 9662 std::optional<llvm::MemoryBufferRef> FromBuf = 9663 Cache->getBufferOrNone(FromContext.getDiagnostics(), 9664 FromSM.getFileManager(), SourceLocation{}); 9665 if (!FromBuf) 9666 return llvm::make_error<ASTImportError>(ASTImportError::Unknown); 9667 9668 std::unique_ptr<llvm::MemoryBuffer> ToBuf = 9669 llvm::MemoryBuffer::getMemBufferCopy(FromBuf->getBuffer(), 9670 FromBuf->getBufferIdentifier()); 9671 ToID = ToSM.createFileID(std::move(ToBuf), 9672 FromSLoc.getFile().getFileCharacteristic()); 9673 } 9674 } 9675 9676 assert(ToID.isValid() && "Unexpected invalid fileID was created."); 9677 9678 ImportedFileIDs[FromID] = ToID; 9679 return ToID; 9680 } 9681 9682 Expected<CXXCtorInitializer *> ASTImporter::Import(CXXCtorInitializer *From) { 9683 ExpectedExpr ToExprOrErr = Import(From->getInit()); 9684 if (!ToExprOrErr) 9685 return ToExprOrErr.takeError(); 9686 9687 auto LParenLocOrErr = Import(From->getLParenLoc()); 9688 if (!LParenLocOrErr) 9689 return LParenLocOrErr.takeError(); 9690 9691 auto RParenLocOrErr = Import(From->getRParenLoc()); 9692 if (!RParenLocOrErr) 9693 return RParenLocOrErr.takeError(); 9694 9695 if (From->isBaseInitializer()) { 9696 auto ToTInfoOrErr = Import(From->getTypeSourceInfo()); 9697 if (!ToTInfoOrErr) 9698 return ToTInfoOrErr.takeError(); 9699 9700 SourceLocation EllipsisLoc; 9701 if (From->isPackExpansion()) 9702 if (Error Err = importInto(EllipsisLoc, From->getEllipsisLoc())) 9703 return std::move(Err); 9704 9705 return new (ToContext) CXXCtorInitializer( 9706 ToContext, *ToTInfoOrErr, From->isBaseVirtual(), *LParenLocOrErr, 9707 *ToExprOrErr, *RParenLocOrErr, EllipsisLoc); 9708 } else if (From->isMemberInitializer()) { 9709 ExpectedDecl ToFieldOrErr = Import(From->getMember()); 9710 if (!ToFieldOrErr) 9711 return ToFieldOrErr.takeError(); 9712 9713 auto MemberLocOrErr = Import(From->getMemberLocation()); 9714 if (!MemberLocOrErr) 9715 return MemberLocOrErr.takeError(); 9716 9717 return new (ToContext) CXXCtorInitializer( 9718 ToContext, cast_or_null<FieldDecl>(*ToFieldOrErr), *MemberLocOrErr, 9719 *LParenLocOrErr, *ToExprOrErr, *RParenLocOrErr); 9720 } else if (From->isIndirectMemberInitializer()) { 9721 ExpectedDecl ToIFieldOrErr = Import(From->getIndirectMember()); 9722 if (!ToIFieldOrErr) 9723 return ToIFieldOrErr.takeError(); 9724 9725 auto MemberLocOrErr = Import(From->getMemberLocation()); 9726 if (!MemberLocOrErr) 9727 return MemberLocOrErr.takeError(); 9728 9729 return new (ToContext) CXXCtorInitializer( 9730 ToContext, cast_or_null<IndirectFieldDecl>(*ToIFieldOrErr), 9731 *MemberLocOrErr, *LParenLocOrErr, *ToExprOrErr, *RParenLocOrErr); 9732 } else if (From->isDelegatingInitializer()) { 9733 auto ToTInfoOrErr = Import(From->getTypeSourceInfo()); 9734 if (!ToTInfoOrErr) 9735 return ToTInfoOrErr.takeError(); 9736 9737 return new (ToContext) 9738 CXXCtorInitializer(ToContext, *ToTInfoOrErr, *LParenLocOrErr, 9739 *ToExprOrErr, *RParenLocOrErr); 9740 } else { 9741 // FIXME: assert? 9742 return make_error<ASTImportError>(); 9743 } 9744 } 9745 9746 Expected<CXXBaseSpecifier *> 9747 ASTImporter::Import(const CXXBaseSpecifier *BaseSpec) { 9748 auto Pos = ImportedCXXBaseSpecifiers.find(BaseSpec); 9749 if (Pos != ImportedCXXBaseSpecifiers.end()) 9750 return Pos->second; 9751 9752 Expected<SourceRange> ToSourceRange = Import(BaseSpec->getSourceRange()); 9753 if (!ToSourceRange) 9754 return ToSourceRange.takeError(); 9755 Expected<TypeSourceInfo *> ToTSI = Import(BaseSpec->getTypeSourceInfo()); 9756 if (!ToTSI) 9757 return ToTSI.takeError(); 9758 ExpectedSLoc ToEllipsisLoc = Import(BaseSpec->getEllipsisLoc()); 9759 if (!ToEllipsisLoc) 9760 return ToEllipsisLoc.takeError(); 9761 CXXBaseSpecifier *Imported = new (ToContext) CXXBaseSpecifier( 9762 *ToSourceRange, BaseSpec->isVirtual(), BaseSpec->isBaseOfClass(), 9763 BaseSpec->getAccessSpecifierAsWritten(), *ToTSI, *ToEllipsisLoc); 9764 ImportedCXXBaseSpecifiers[BaseSpec] = Imported; 9765 return Imported; 9766 } 9767 9768 llvm::Expected<APValue> ASTImporter::Import(const APValue &FromValue) { 9769 ASTNodeImporter Importer(*this); 9770 return Importer.ImportAPValue(FromValue); 9771 } 9772 9773 Error ASTImporter::ImportDefinition(Decl *From) { 9774 ExpectedDecl ToOrErr = Import(From); 9775 if (!ToOrErr) 9776 return ToOrErr.takeError(); 9777 Decl *To = *ToOrErr; 9778 9779 auto *FromDC = cast<DeclContext>(From); 9780 ASTNodeImporter Importer(*this); 9781 9782 if (auto *ToRecord = dyn_cast<RecordDecl>(To)) { 9783 if (!ToRecord->getDefinition()) { 9784 return Importer.ImportDefinition( 9785 cast<RecordDecl>(FromDC), ToRecord, 9786 ASTNodeImporter::IDK_Everything); 9787 } 9788 } 9789 9790 if (auto *ToEnum = dyn_cast<EnumDecl>(To)) { 9791 if (!ToEnum->getDefinition()) { 9792 return Importer.ImportDefinition( 9793 cast<EnumDecl>(FromDC), ToEnum, ASTNodeImporter::IDK_Everything); 9794 } 9795 } 9796 9797 if (auto *ToIFace = dyn_cast<ObjCInterfaceDecl>(To)) { 9798 if (!ToIFace->getDefinition()) { 9799 return Importer.ImportDefinition( 9800 cast<ObjCInterfaceDecl>(FromDC), ToIFace, 9801 ASTNodeImporter::IDK_Everything); 9802 } 9803 } 9804 9805 if (auto *ToProto = dyn_cast<ObjCProtocolDecl>(To)) { 9806 if (!ToProto->getDefinition()) { 9807 return Importer.ImportDefinition( 9808 cast<ObjCProtocolDecl>(FromDC), ToProto, 9809 ASTNodeImporter::IDK_Everything); 9810 } 9811 } 9812 9813 return Importer.ImportDeclContext(FromDC, true); 9814 } 9815 9816 Expected<DeclarationName> ASTImporter::Import(DeclarationName FromName) { 9817 if (!FromName) 9818 return DeclarationName{}; 9819 9820 switch (FromName.getNameKind()) { 9821 case DeclarationName::Identifier: 9822 return DeclarationName(Import(FromName.getAsIdentifierInfo())); 9823 9824 case DeclarationName::ObjCZeroArgSelector: 9825 case DeclarationName::ObjCOneArgSelector: 9826 case DeclarationName::ObjCMultiArgSelector: 9827 if (auto ToSelOrErr = Import(FromName.getObjCSelector())) 9828 return DeclarationName(*ToSelOrErr); 9829 else 9830 return ToSelOrErr.takeError(); 9831 9832 case DeclarationName::CXXConstructorName: { 9833 if (auto ToTyOrErr = Import(FromName.getCXXNameType())) 9834 return ToContext.DeclarationNames.getCXXConstructorName( 9835 ToContext.getCanonicalType(*ToTyOrErr)); 9836 else 9837 return ToTyOrErr.takeError(); 9838 } 9839 9840 case DeclarationName::CXXDestructorName: { 9841 if (auto ToTyOrErr = Import(FromName.getCXXNameType())) 9842 return ToContext.DeclarationNames.getCXXDestructorName( 9843 ToContext.getCanonicalType(*ToTyOrErr)); 9844 else 9845 return ToTyOrErr.takeError(); 9846 } 9847 9848 case DeclarationName::CXXDeductionGuideName: { 9849 if (auto ToTemplateOrErr = Import(FromName.getCXXDeductionGuideTemplate())) 9850 return ToContext.DeclarationNames.getCXXDeductionGuideName( 9851 cast<TemplateDecl>(*ToTemplateOrErr)); 9852 else 9853 return ToTemplateOrErr.takeError(); 9854 } 9855 9856 case DeclarationName::CXXConversionFunctionName: { 9857 if (auto ToTyOrErr = Import(FromName.getCXXNameType())) 9858 return ToContext.DeclarationNames.getCXXConversionFunctionName( 9859 ToContext.getCanonicalType(*ToTyOrErr)); 9860 else 9861 return ToTyOrErr.takeError(); 9862 } 9863 9864 case DeclarationName::CXXOperatorName: 9865 return ToContext.DeclarationNames.getCXXOperatorName( 9866 FromName.getCXXOverloadedOperator()); 9867 9868 case DeclarationName::CXXLiteralOperatorName: 9869 return ToContext.DeclarationNames.getCXXLiteralOperatorName( 9870 Import(FromName.getCXXLiteralIdentifier())); 9871 9872 case DeclarationName::CXXUsingDirective: 9873 // FIXME: STATICS! 9874 return DeclarationName::getUsingDirectiveName(); 9875 } 9876 9877 llvm_unreachable("Invalid DeclarationName Kind!"); 9878 } 9879 9880 IdentifierInfo *ASTImporter::Import(const IdentifierInfo *FromId) { 9881 if (!FromId) 9882 return nullptr; 9883 9884 IdentifierInfo *ToId = &ToContext.Idents.get(FromId->getName()); 9885 9886 if (!ToId->getBuiltinID() && FromId->getBuiltinID()) 9887 ToId->setBuiltinID(FromId->getBuiltinID()); 9888 9889 return ToId; 9890 } 9891 9892 Expected<Selector> ASTImporter::Import(Selector FromSel) { 9893 if (FromSel.isNull()) 9894 return Selector{}; 9895 9896 SmallVector<IdentifierInfo *, 4> Idents; 9897 Idents.push_back(Import(FromSel.getIdentifierInfoForSlot(0))); 9898 for (unsigned I = 1, N = FromSel.getNumArgs(); I < N; ++I) 9899 Idents.push_back(Import(FromSel.getIdentifierInfoForSlot(I))); 9900 return ToContext.Selectors.getSelector(FromSel.getNumArgs(), Idents.data()); 9901 } 9902 9903 llvm::Expected<APValue> 9904 ASTNodeImporter::ImportAPValue(const APValue &FromValue) { 9905 APValue Result; 9906 llvm::Error Err = llvm::Error::success(); 9907 auto ImportLoop = [&](const APValue *From, APValue *To, unsigned Size) { 9908 for (unsigned Idx = 0; Idx < Size; Idx++) { 9909 APValue Tmp = importChecked(Err, From[Idx]); 9910 To[Idx] = Tmp; 9911 } 9912 }; 9913 switch (FromValue.getKind()) { 9914 case APValue::None: 9915 case APValue::Indeterminate: 9916 case APValue::Int: 9917 case APValue::Float: 9918 case APValue::FixedPoint: 9919 case APValue::ComplexInt: 9920 case APValue::ComplexFloat: 9921 Result = FromValue; 9922 break; 9923 case APValue::Vector: { 9924 Result.MakeVector(); 9925 MutableArrayRef<APValue> Elts = 9926 Result.setVectorUninit(FromValue.getVectorLength()); 9927 ImportLoop(((const APValue::Vec *)(const char *)&FromValue.Data)->Elts, 9928 Elts.data(), FromValue.getVectorLength()); 9929 break; 9930 } 9931 case APValue::Array: 9932 Result.MakeArray(FromValue.getArrayInitializedElts(), 9933 FromValue.getArraySize()); 9934 ImportLoop(((const APValue::Arr *)(const char *)&FromValue.Data)->Elts, 9935 ((const APValue::Arr *)(const char *)&Result.Data)->Elts, 9936 FromValue.getArrayInitializedElts()); 9937 break; 9938 case APValue::Struct: 9939 Result.MakeStruct(FromValue.getStructNumBases(), 9940 FromValue.getStructNumFields()); 9941 ImportLoop( 9942 ((const APValue::StructData *)(const char *)&FromValue.Data)->Elts, 9943 ((const APValue::StructData *)(const char *)&Result.Data)->Elts, 9944 FromValue.getStructNumBases() + FromValue.getStructNumFields()); 9945 break; 9946 case APValue::Union: { 9947 Result.MakeUnion(); 9948 const Decl *ImpFDecl = importChecked(Err, FromValue.getUnionField()); 9949 APValue ImpValue = importChecked(Err, FromValue.getUnionValue()); 9950 if (Err) 9951 return std::move(Err); 9952 Result.setUnion(cast<FieldDecl>(ImpFDecl), ImpValue); 9953 break; 9954 } 9955 case APValue::AddrLabelDiff: { 9956 Result.MakeAddrLabelDiff(); 9957 const Expr *ImpLHS = importChecked(Err, FromValue.getAddrLabelDiffLHS()); 9958 const Expr *ImpRHS = importChecked(Err, FromValue.getAddrLabelDiffRHS()); 9959 if (Err) 9960 return std::move(Err); 9961 Result.setAddrLabelDiff(cast<AddrLabelExpr>(ImpLHS), 9962 cast<AddrLabelExpr>(ImpRHS)); 9963 break; 9964 } 9965 case APValue::MemberPointer: { 9966 const Decl *ImpMemPtrDecl = 9967 importChecked(Err, FromValue.getMemberPointerDecl()); 9968 if (Err) 9969 return std::move(Err); 9970 MutableArrayRef<const CXXRecordDecl *> ToPath = 9971 Result.setMemberPointerUninit( 9972 cast<const ValueDecl>(ImpMemPtrDecl), 9973 FromValue.isMemberPointerToDerivedMember(), 9974 FromValue.getMemberPointerPath().size()); 9975 llvm::ArrayRef<const CXXRecordDecl *> FromPath = 9976 Result.getMemberPointerPath(); 9977 for (unsigned Idx = 0; Idx < FromValue.getMemberPointerPath().size(); 9978 Idx++) { 9979 const Decl *ImpDecl = importChecked(Err, FromPath[Idx]); 9980 if (Err) 9981 return std::move(Err); 9982 ToPath[Idx] = cast<const CXXRecordDecl>(ImpDecl->getCanonicalDecl()); 9983 } 9984 break; 9985 } 9986 case APValue::LValue: 9987 APValue::LValueBase Base; 9988 QualType FromElemTy; 9989 if (FromValue.getLValueBase()) { 9990 assert(!FromValue.getLValueBase().is<DynamicAllocLValue>() && 9991 "in C++20 dynamic allocation are transient so they shouldn't " 9992 "appear in the AST"); 9993 if (!FromValue.getLValueBase().is<TypeInfoLValue>()) { 9994 if (const auto *E = 9995 FromValue.getLValueBase().dyn_cast<const Expr *>()) { 9996 FromElemTy = E->getType(); 9997 const Expr *ImpExpr = importChecked(Err, E); 9998 if (Err) 9999 return std::move(Err); 10000 Base = APValue::LValueBase(ImpExpr, 10001 FromValue.getLValueBase().getCallIndex(), 10002 FromValue.getLValueBase().getVersion()); 10003 } else { 10004 FromElemTy = 10005 FromValue.getLValueBase().get<const ValueDecl *>()->getType(); 10006 const Decl *ImpDecl = importChecked( 10007 Err, FromValue.getLValueBase().get<const ValueDecl *>()); 10008 if (Err) 10009 return std::move(Err); 10010 Base = APValue::LValueBase(cast<ValueDecl>(ImpDecl), 10011 FromValue.getLValueBase().getCallIndex(), 10012 FromValue.getLValueBase().getVersion()); 10013 } 10014 } else { 10015 FromElemTy = FromValue.getLValueBase().getTypeInfoType(); 10016 const Type *ImpTypeInfo = importChecked( 10017 Err, FromValue.getLValueBase().get<TypeInfoLValue>().getType()); 10018 QualType ImpType = 10019 importChecked(Err, FromValue.getLValueBase().getTypeInfoType()); 10020 if (Err) 10021 return std::move(Err); 10022 Base = APValue::LValueBase::getTypeInfo(TypeInfoLValue(ImpTypeInfo), 10023 ImpType); 10024 } 10025 } 10026 CharUnits Offset = FromValue.getLValueOffset(); 10027 unsigned PathLength = FromValue.getLValuePath().size(); 10028 Result.MakeLValue(); 10029 if (FromValue.hasLValuePath()) { 10030 MutableArrayRef<APValue::LValuePathEntry> ToPath = Result.setLValueUninit( 10031 Base, Offset, PathLength, FromValue.isLValueOnePastTheEnd(), 10032 FromValue.isNullPointer()); 10033 llvm::ArrayRef<APValue::LValuePathEntry> FromPath = 10034 FromValue.getLValuePath(); 10035 for (unsigned LoopIdx = 0; LoopIdx < PathLength; LoopIdx++) { 10036 if (FromElemTy->isRecordType()) { 10037 const Decl *FromDecl = 10038 FromPath[LoopIdx].getAsBaseOrMember().getPointer(); 10039 const Decl *ImpDecl = importChecked(Err, FromDecl); 10040 if (Err) 10041 return std::move(Err); 10042 if (auto *RD = dyn_cast<CXXRecordDecl>(FromDecl)) 10043 FromElemTy = Importer.FromContext.getRecordType(RD); 10044 else 10045 FromElemTy = cast<ValueDecl>(FromDecl)->getType(); 10046 ToPath[LoopIdx] = APValue::LValuePathEntry(APValue::BaseOrMemberType( 10047 ImpDecl, FromPath[LoopIdx].getAsBaseOrMember().getInt())); 10048 } else { 10049 FromElemTy = 10050 Importer.FromContext.getAsArrayType(FromElemTy)->getElementType(); 10051 ToPath[LoopIdx] = APValue::LValuePathEntry::ArrayIndex( 10052 FromPath[LoopIdx].getAsArrayIndex()); 10053 } 10054 } 10055 } else 10056 Result.setLValue(Base, Offset, APValue::NoLValuePath{}, 10057 FromValue.isNullPointer()); 10058 } 10059 if (Err) 10060 return std::move(Err); 10061 return Result; 10062 } 10063 10064 Expected<DeclarationName> ASTImporter::HandleNameConflict(DeclarationName Name, 10065 DeclContext *DC, 10066 unsigned IDNS, 10067 NamedDecl **Decls, 10068 unsigned NumDecls) { 10069 if (ODRHandling == ODRHandlingType::Conservative) 10070 // Report error at any name conflict. 10071 return make_error<ASTImportError>(ASTImportError::NameConflict); 10072 else 10073 // Allow to create the new Decl with the same name. 10074 return Name; 10075 } 10076 10077 DiagnosticBuilder ASTImporter::ToDiag(SourceLocation Loc, unsigned DiagID) { 10078 if (LastDiagFromFrom) 10079 ToContext.getDiagnostics().notePriorDiagnosticFrom( 10080 FromContext.getDiagnostics()); 10081 LastDiagFromFrom = false; 10082 return ToContext.getDiagnostics().Report(Loc, DiagID); 10083 } 10084 10085 DiagnosticBuilder ASTImporter::FromDiag(SourceLocation Loc, unsigned DiagID) { 10086 if (!LastDiagFromFrom) 10087 FromContext.getDiagnostics().notePriorDiagnosticFrom( 10088 ToContext.getDiagnostics()); 10089 LastDiagFromFrom = true; 10090 return FromContext.getDiagnostics().Report(Loc, DiagID); 10091 } 10092 10093 void ASTImporter::CompleteDecl (Decl *D) { 10094 if (auto *ID = dyn_cast<ObjCInterfaceDecl>(D)) { 10095 if (!ID->getDefinition()) 10096 ID->startDefinition(); 10097 } 10098 else if (auto *PD = dyn_cast<ObjCProtocolDecl>(D)) { 10099 if (!PD->getDefinition()) 10100 PD->startDefinition(); 10101 } 10102 else if (auto *TD = dyn_cast<TagDecl>(D)) { 10103 if (!TD->getDefinition() && !TD->isBeingDefined()) { 10104 TD->startDefinition(); 10105 TD->setCompleteDefinition(true); 10106 } 10107 } 10108 else { 10109 assert(0 && "CompleteDecl called on a Decl that can't be completed"); 10110 } 10111 } 10112 10113 Decl *ASTImporter::MapImported(Decl *From, Decl *To) { 10114 llvm::DenseMap<Decl *, Decl *>::iterator Pos = ImportedDecls.find(From); 10115 assert((Pos == ImportedDecls.end() || Pos->second == To) && 10116 "Try to import an already imported Decl"); 10117 if (Pos != ImportedDecls.end()) 10118 return Pos->second; 10119 ImportedDecls[From] = To; 10120 // This mapping should be maintained only in this function. Therefore do not 10121 // check for additional consistency. 10122 ImportedFromDecls[To] = From; 10123 // In the case of TypedefNameDecl we create the Decl first and only then we 10124 // import and set its DeclContext. So, the DC is still not set when we reach 10125 // here from GetImportedOrCreateDecl. 10126 if (To->getDeclContext()) 10127 AddToLookupTable(To); 10128 return To; 10129 } 10130 10131 std::optional<ASTImportError> 10132 ASTImporter::getImportDeclErrorIfAny(Decl *FromD) const { 10133 auto Pos = ImportDeclErrors.find(FromD); 10134 if (Pos != ImportDeclErrors.end()) 10135 return Pos->second; 10136 else 10137 return std::nullopt; 10138 } 10139 10140 void ASTImporter::setImportDeclError(Decl *From, ASTImportError Error) { 10141 auto InsertRes = ImportDeclErrors.insert({From, Error}); 10142 (void)InsertRes; 10143 // Either we set the error for the first time, or we already had set one and 10144 // now we want to set the same error. 10145 assert(InsertRes.second || InsertRes.first->second.Error == Error.Error); 10146 } 10147 10148 bool ASTImporter::IsStructurallyEquivalent(QualType From, QualType To, 10149 bool Complain) { 10150 llvm::DenseMap<const Type *, const Type *>::iterator Pos = 10151 ImportedTypes.find(From.getTypePtr()); 10152 if (Pos != ImportedTypes.end()) { 10153 if (ExpectedType ToFromOrErr = Import(From)) { 10154 if (ToContext.hasSameType(*ToFromOrErr, To)) 10155 return true; 10156 } else { 10157 llvm::consumeError(ToFromOrErr.takeError()); 10158 } 10159 } 10160 10161 StructuralEquivalenceContext Ctx(FromContext, ToContext, NonEquivalentDecls, 10162 getStructuralEquivalenceKind(*this), false, 10163 Complain); 10164 return Ctx.IsEquivalent(From, To); 10165 } 10166