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