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