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