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